Music & Audio Generation: Codecs, Tokens and Diffusion
Why raw audio is hard to generate, how neural audio codecs (SoundStream, EnCodec) turn sound into tokens, and how AudioLM, MusicGen, AudioLDM and Jukebox generate speech, music and sound effects.
A three-minute song at 44.1 kHz stereo is about 16 million numbers, and it must stay coherent over that whole span: the chorus should come back, the tempo should not drift, the chords should resolve. Text models handle a few thousand tokens; image models a few thousand latent patches. The breakthrough for audio generative models was to first compress sound into a short sequence of discrete tokens with a neural Neural audio codec, and then reuse the two strongest generative recipes we know: Transformer language models and Latent diffusion.
1. Neural audio codecs: SoundStream and EnCodec
SoundStream (Zeghidour et al., 2021)[1] and EnCodec (Défossez et al., 2022)[2] are convolutional autoencoders: an encoder downsamples the waveform into latent frames (e.g. 75 frames per second for 24 kHz EnCodec), a residual vector quantizer (RVQ) turns each frame into a few integers, and a decoder reconstructs the waveform. They are trained with reconstruction losses (waveform and multi-scale mel) plus adversarial discriminators, so the result sounds good rather than merely matching on average. With quantizer dropout, one model supports several bitrates. At 6 kbps EnCodec beats classic codecs like Opus at much higher bitrates in listening tests.
- Quantizer 1 picks the nearest of K codebook vectors (e.g. K = 1024) to the latent frame z → token q₁.
- Compute the residual r₁ = z − c(q₁). Quantizer 2 quantizes r₁ → token q₂, and so on for N_q stages.
- The frame is reconstructed as the sum c(q₁) + c(q₂) + … The first codebooks carry coarse content (pitch, phonemes, rhythm); later ones add fine detail (timbre, noise, crispness).
- bitrate
- bits per second needed to transmit the tokens
- frame_rate
- latent frames per second (75 for EnCodec 24 kHz, 50 for MusicGen's 32 kHz codec)
- N_q
- number of RVQ codebooks (quantizers) used
- log₂(K)
- bits per token: log base 2 of the codebook size
- K
- entries per codebook (1024 in EnCodec 24 kHz → 10 bits)
- kbps
- kilobits per second (1 kbps = 1000 bit/s)
▸Worked example
2. Language models over audio tokens
AudioLM (Borsos et al., 2022)[3] showed that a Transformer can continue speech or piano music convincingly by predicting two kinds of tokens: *semantic* tokens (k-means clusters of a self-supervised speech model, capturing content and long-term structure at a low rate) and *acoustic* tokens (SoundStream codes, capturing voice and recording quality). Generation is hierarchical: semantic tokens first, then coarse acoustic tokens conditioned on them, then fine acoustic tokens. Given a 3-second prompt, it continues speech in the same voice with plausible (though meaningless) words.
MusicGen (Copet et al., 2023)[4] simplified this into a single-stage Transformer decoder over EnCodec tokens (32 kHz, 4 codebooks at 50 Hz). Instead of predicting the 4 codebooks one after another (4× longer sequence) or all at once (ignores their dependency), it uses a delay pattern: codebook k is shifted by k steps, so at each step the model predicts all 4 streams in parallel while finer codebooks still see the coarser ones from earlier steps. Text descriptions are encoded with a frozen T5 encoder and injected through cross-attention; an optional melody can be given as a chromagram. It was trained on about 20,000 hours of licensed music and uses Classifier-free guidance (CFG) at sampling time.
3. Diffusion for audio: AudioLDM
AudioLDM (Liu et al., 2023)[5] borrows the Stable Diffusion recipe: a VAE compresses mel spectrograms into a small latent image, a Diffusion model denoises that latent, and a HiFi-GAN vocoder turns the decoded mel back into audio. Conditioning comes from CLAP, a contrastive audio–text model (like CLIP for sound). The trick: CLAP puts audio and text in the same embedding space, so training can condition on the *audio's own* CLAP embedding (no captions needed), while at inference you condition on the *text* embedding. It excels at sound effects and ambiences (“rain on a tin roof with distant thunder”).
4. Jukebox: raw audio with lyrics
Jukebox (Dhariwal et al., 2020)[6] was the first model to generate minutes of raw 44.1 kHz music with singing. A hierarchical VQ-VAE compresses audio at three levels (8×, 32× and 128× fewer steps); a large sparse Transformer prior generates the top level conditioned on artist, genre and lyrics, and upsampler priors fill in the lower levels. The results were striking but noisy, and rendering one minute took hours on a GPU — showing why later work moved to compact codecs and faster samplers.
| Model | Representation | Generator | Best at |
|---|---|---|---|
| Jukebox (2020) | 3-level VQ-VAE codes, 44.1 kHz | Sparse Transformer priors | Songs with lyrics (slow) |
| AudioLM (2022) | Semantic + SoundStream tokens | 3-stage Transformer LM | Speech / piano continuation |
| MusicGen (2023) | EnCodec 32 kHz, 4 codebooks | Single Transformer, delay pattern | Text/melody → instrumental music |
| AudioLDM (2023) | VAE latent of mel spectrogram | Latent diffusion + CLAP | Sound effects, ambience, text-to-audio |
The knobs
- What it is
- Classifier-free guidance strength: how strongly sampling is pushed toward the text condition versus the unconditional model.
- ↑ If you increase it
- Output follows the prompt more literally (the right instruments and mood), but diversity drops and, at high values, audio becomes harsh or distorted.
- ↓ If you decrease it
- More varied, sometimes more natural audio that may ignore parts of the prompt.
- Typical values
- ≈ 3 for MusicGen; 2.5–4 for AudioLDM.
- What it is
- Sampling settings for codec-token language models like MusicGen: temperature reshapes the next-token distribution, top-k keeps only the k most likely tokens.
- ↑ If you increase it
- More surprising, varied music; too high produces noise bursts, glitches and loss of rhythm.
- ↓ If you decrease it
- Safer, repetitive output; greedy decoding often loops the same bar or collapses into silence.
- Typical values
- temperature 1.0 with top_k = 250 (MusicGen default).
- What it is
- Length of the generated clip. For MusicGen, tokens are produced at 50 per second, so 256 tokens ≈ 5 s.
- ↑ If you increase it
- Longer pieces, but cost grows (attention is quadratic in length) and long-range structure tends to wander; beyond the training length (~30 s) quality drops unless you use windowed continuation.
- ↓ If you decrease it
- Fast previews, ideal for iterating on prompts; too short to develop a musical phrase.
- Typical values
- 5–30 s per generation.
- What it is
- How many RVQ codebooks are used per frame, i.e. the codec bitrate.
- ↑ If you increase it
- Higher fidelity reconstruction (cleaner cymbals, less “underwater” sound), but more tokens for a generative model to predict.
- ↓ If you decrease it
- Tiny bitrates suitable for streaming and easier generation, but artifacts and muffled timbre.
- Typical values
- EnCodec 24 kHz: 1.5, 3, 6, 12 or 24 kbps; MusicGen uses 4 codebooks.
In code
import scipy.io.wavfile
from transformers import AutoProcessor, MusicgenForConditionalGeneration
processor = AutoProcessor.from_pretrained("facebook/musicgen-small")
model = MusicgenForConditionalGeneration.from_pretrained("facebook/musicgen-small")
inputs = processor(text=["gamelan-inspired ambient track with soft bamboo flute",
"upbeat dangdut rhythm with bass and kendang"],
padding=True, return_tensors="pt")
audio = model.generate(**inputs, do_sample=True, guidance_scale=3.0,
max_new_tokens=256) # ~5 seconds at 50 tokens/s
sr = model.config.audio_encoder.sampling_rate # 32000
scipy.io.wavfile.write("musicgen_0.wav", rate=sr, data=audio[0, 0].numpy())import librosa
from transformers import EncodecModel, AutoProcessor
model = EncodecModel.from_pretrained("facebook/encodec_24khz")
processor = AutoProcessor.from_pretrained("facebook/encodec_24khz")
wav, _ = librosa.load("speech.wav", sr=processor.sampling_rate) # 24 kHz mono
inputs = processor(raw_audio=wav, sampling_rate=processor.sampling_rate,
return_tensors="pt")
enc = model.encode(inputs["input_values"], inputs["padding_mask"], bandwidth=6.0)
print(enc.audio_codes.shape) # last two dims: N_q=8 codebooks x frames (75 per second)
recon = model.decode(enc.audio_codes, enc.audio_scales, inputs["padding_mask"])[0]▸Go deeper: why the delay pattern works
With 4 codebooks and T frames, the exact autoregressive factorisation would need 4T sequential steps. Predicting all 4 codebooks of frame t independently needs only T steps but ignores that codebook 2 refines codebook 1. In the delay pattern, at step s the model predicts codebook 1 of frame s, codebook 2 of frame s−1, codebook 3 of frame s−2 and codebook 4 of frame s−3. Each finer code is therefore predicted after the coarser codes of the same frame are known, at the cost of only 3 extra steps (T + 3 total).
The same codec-token idea now powers speech language models and real-time voice assistants: audio in → codec tokens → Transformer → codec tokens → audio out, with no separate ASR or TTS step.
Quiz
References
- [1]SoundStream: An End-to-End Neural Audio CodecPaperZeghidour et al.2021arxiv.org
- [2]
- [3]AudioLM: a Language Modeling Approach to Audio GenerationPaperBorsos et al.2022arxiv.org
- [4]
- [5]AudioLDM: Text-to-Audio Generation with Latent Diffusion ModelsPaperLiu et al.2023arxiv.org
- [6]Jukebox: A Generative Model for MusicPaperDhariwal et al.2020arxiv.org