Generative Audio
How do machines make sound itself, and how do we judge and label what they make?
An ear question: Part 9's bowed string and a DDSP network's copy from its pitch and loudness (the first was the network, 6.7 dB away by spectrum); from WaveNet's sixteen thousand decisions a second in 2016 to text-to-song services and the lawsuits of 2024. Raw audio: a second magnified, the numbers, mu-law against equal steps heard (37 against 18 dB). A sample-level network over the last 256 samples memorizes its training notes (8.4 bits a sample on new audio) and takes 278 s to write one second; split structure from detail. Spectrograms: 64 mel bands rebuilt by Griffin-Lim, heard (15.4 dB; 16 and 256 bands, 20.6 and 8.3); vocoders. Codec tokens: residual vector quantization of log spectra; an ear question on one, two and four tokens a frame (within 0.2 dB); bits against fidelity. Language models over tokens: AudioLM, MusicLM, MusicGen's delay pattern; a pocket transformer on 41 minutes of piano tokens continues a tune it never heard, heard; its longest copy, one second. Diffusion: a profile of 24 harmonics drawn from noise; drawn and measured tones heard; latent diffusion and flow matching. DDSP: 24,249 weights set 40 harmonics and 16 noise bands; a phrase it never heard resynthesized (6.0 dB), heard; its controls; a vibrato and a glide it never saw, heard; timbre transfer. Voices: singing synthesis, one performance in three voices heard, cloning and the law (dated). Judging: Fréchet distances, where the training notes replayed score best; listening tests. Watermarks: an ear question on a mark 35 dB down; it survives a coder, not a room; detectors and provenance. Frontier: data, the courts, musicians, attribution. Variation 66: the Tune sung, re-rendered by DDSP, continued by the token model.
What you need. Part 3 for spectra; Part 48 for sampling and quantization; Part 58 for codecs and listening tests; Part 61 for pitch tracking; Part 65 for next-token models and copying. Companding, the STFT, k-means, transformers, denoising diffusion, automatic differentiation, the Fréchet distance between Gaussians, correlation detection.
- Ideas, mathematics and history
- WaveNet, vocoders, VQ-VAE and neural codecs, language models over audio tokens, diffusion, differentiable DSP, voices, rights
- What we build, compute and hear
- a DDSP instrument and a token model trained on our own sounds
What you will be able to do
Foundations
- Hear mu-law against equal steps, a sample-level continuation, and mel spectrograms rebuilt with different band counts.
- Hear a codec at several stages, a token-model continuation, diffusion-drawn tones and a DDSP string.
- Explain why generators split structure from detail, and why copying and consent are measured, not assumed.
Full course
- Quantize audio by mu-law and by residual vector quantization, and measure bits against spectral distance.
- Train a DDSP synthesizer by a multi-resolution spectral loss, and a diffusion model over vectors.
- Compute a Fréchet distance between embedding sets; embed and detect a spread-spectrum watermark.
Research
- Design a test of training-data attribution for generated audio on a corpus whose every recording is known.
Practice
- Know and disclose training data, get consent for voices, label outputs, and judge by distance, listeners and copying.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Foundations 26 min · Full course 31 min · Research 35 min · Practice 31 min.
- 0Sixteen thousand decisions a secondFoundations2 min
- 1Why raw audio is hardFoundations2 min
- 2One sample at a timeFoundations2 min
- 3Spectrograms and vocodersFoundations2 min
- 4Tokens from a codecFoundations3 min
- 5Language models over soundFoundations3 min
- 6DiffusionFoundations3 min
- 7Differentiable DSPFoundations3 min
- 8Singing and cloned voicesFoundations3 min
- 9Judging generated soundPractice3 min
- 10Watermarks and detectionPractice3 min
- 11Frontier: data, consent and what is unsolvedResearch4 min
- Variation 66, recap and problemsAll tracks2 min
Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · Build the film.
Lecture
The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film. A dashed box stands for a number the film computes when it is rendered (hover over it to see what is computed); the README's figures for each chapter, where it lists them, follow the chapter's text.
Sixteen thousand decisions a secondFoundations2 min
In 2016 a network wrote sound one sample at a time, sixteen thousand decisions a second. Listen first. Two phrases on a bowed string. One is Monochord's physical model of a string, from Part 9. The other was made by a small network that was given only the first one's pitch and loudness. Which is the network?
The first was the network. It does not write sound sample by sample: it sets the controls of a synthesizer, forty harmonics and some noise, many times a second, and Chapter 7 builds it. That is one of three ideas this part follows from noodling to finished songs.
In 2016 DeepMind's WaveNet wrote sound one sample at a time, sixteen thousand decisions a second. Its speech was startling; its piano, learnt from recordings, noodled nowhere. In 2020 OpenAI's Jukebox wrote minutes of songs with singing, from tokens of compressed audio, taking hours to make a minute. In 2023 MusicLM, from Google, and MusicGen, from Meta, turned a sentence into music. By 2024 services returned a finished song with a singer, and the major record labels sued two of them. What closed the gap? Better ways to represent sound, language models over them, diffusion, and data: whose, is the last chapter's question.
Here is the plan, and for each idea Monochord builds the smallest honest version. Why raw audio is hard, and a network that writes it one sample at a time. Spectrograms and vocoders. Tokens from a codec, and a language model over them. Diffusion. A network that plays a synthesizer. And cloned voices, how to judge generated sound, how to mark it, and whose music it learnt from. The results are reported as they are.
1Why raw audio is hardFoundations2 min
How many decisions is a second of sound?
Look at a second of sound at three magnifications. The whole second: a phrase of a bowed string. Fifty milliseconds of it: the string's waves, repeating at the note's pitch. And two milliseconds: thirty-two samples, each a number. A generator that works on raw sound must choose every one of those numbers.
Sound is a long sequence. A second of CD audio is 44,100 samples of 16 bits in each of two channels: one point four million bits. A model that writes raw sound must decide every sample, sixteen thousand a second at a sixteen-kilohertz mono sampling rate. A three-minute song is about 2.88 million decisions at that rate, each depending on the ones before. And a musical phrase lasts seconds, so to keep a melody in mind the model must look back tens of thousands of samples. A text model writes a few tokens for a second of speech; the gap is a factor of thousands.
WaveNet's first step was to make each decision smaller. Compand the sample: take a logarithm of its size, then cut the result into 256 equal steps. The steps are fine near silence and coarse when the sound is loud, where the ear forgives them; telephones have done this since the nineteen seventies. Each sample becomes one of 256 classes, and the network's job is to give a probability to each.
Hear a quiet bowed phrase with 256 equal levels, then with 256 mu-law levels, both turned up so you can hear the difference.
Equal steps leave the quiet phrase decibels above its own grit; mu-law, . The same 256 classes, spent where the ear needs them.
2One sample at a timeFoundations2 min
What does a network write when it writes every sample?
WaveNet, from Aäron van den Oord and colleagues in 2016, predicts each sample from a finite receptive field of preceding samples. Its trick for looking far back cheaply is the dilated convolution: layers that look one, two, four, eight samples back, so that a stack of thirty sees thousands. Told what to say, a text or a speaker, it spoke astonishingly well; left to itself on music, it noodled. And generation is serial: every sample waits for the one before, and the first versions took minutes for a second of sound. Its lasting use was as a vocoder, turning a spectrogram into sound, as the next chapter explains.
Monochord's version is far smaller: a network that reads the last samples and outputs a probability for each of the 256 levels of the next, trained on a minute of the bowed-string model's notes. On its training notes it learns quickly to beat a blind guess of eight bits a sample. On a phrase it never heard, bitsAnd two hundred and fifty-six samples is a sixtieth of a second, a few cycles of the lowest notes, nothing like a phrase.
Hear half a second of a bowed phrase, then the same half second with the network's next second after it.
After the string, it writes whatever a sixtieth of a second of learned local context, allows. Sixteen thousand decisions took about seconds of computing here. Bigger networks, trained for weeks on far more audio, made such continuations sound like instruments; long-range planning remained difficult for early sample-level systems.
The lesson was clear by 2017. Raw samples represent musical structure implicitly across very long sequences. So split the job: plan the structure in a compact representation, and let another model fill in the detail. The rest of this part is that split, four ways: spectrograms, codec tokens, latents, and the controls of a synthesizer.
3Spectrograms and vocodersFoundations2 min
Can sound be made from a picture of sound?
The first split is the spectrogram. Here is a bowed phrase as a mel spectrogram: the energy in sixty-four mel-spaced bands, an approximate perceptual frequency scale, sixty-two times a second. The phrase's notes, their harmonics and their attacks are all visible, and there are four thousand numbers a second instead of sixteen thousand samples. What is gone is the phase, the exact timing of every wave, and the fine detail between bands.
Can the picture be turned back into sound? Spread each band back over its frequencies, and invent a phase by Griffin and Lim's method from Part 64. Hear the phrase, then the phrase rebuilt from its mel spectrogram.
The tune survives; the sound is smeared and a little metallic, decibels from the original by spectrum. Most of that is lost detail between the bands: with the full spectrum and only the phase invented, the distance is .
How much does the picture need? Hear the phrase rebuilt from sixteen bands, sixty-four, and two hundred and fifty-six.
With sixteen bands the harmonics blur into a hum, decibels away; with two hundred and fifty-six the string returns, . More bands, more numbers to generate: every representation in this part is a trade between what is easy to model and what is needed to hear.
The fix is to learn the way back. A neural vocoder can turn acoustic features such as a mel spectrogram into sound; vocoders also include non-neural systems, trained on many pairs of spectrogram and sound. WaveNet itself served as one from 2017, and then faster ones: WaveGlow, MelGAN, and HiFi-GAN in 2020, quicker than real time. So a generator can work on pictures: draw a spectrogram, then let a vocoder make it sound. Text-to-speech has worked this way since about 2018, and much music generation too.
4Tokens from a codecFoundations3 min
Can sound be turned into words?
The second split turns sound into words. A language model needs a vocabulary: a small set of symbols, a few for each moment. Vector quantization gives one: learn a codebook of typical frames, and replace each frame of sound by the number of its nearest entry. SoundStream, from Neil Zeghidour and colleagues in 2021, and EnCodec, from Alexandre Défossez and colleagues in 2022, train an encoder, a quantizer and a decoder together. Their tokens cost a few kilobits a second: an MP3's job, done by a network, with symbols at the end.
Monochord's codec is the quantizer without the networks. Each sixteen-millisecond hop supplies a frame of 257 numbers, its log spectrum. The first codebook approximates the frame; the second, what the first missed; and so on: residual vector quantization, the scheme SoundStream uses. Each codebook has 256 entries, so a stage costs eight bits a frame, at sixty-two and a half frames a second, learnt by k-means on the piano chorales. There is no learnt encoder or decoder: the spectrum goes in, and Griffin-Lim's phase comes out.
Your turn. A piano chorale tune, then the same eight seconds through the codec three times, with one, two and four tokens a frame, in some order. Which used four?
They were in order: one, two and four. If you could not tell, you were right not to: by spectrum they differ by only of a decibel. For one instrument playing one kind of music, a single codebook of 256 frames already holds most of what there is; real codecs need their stages for the variety of real music.
Here is the trade. One token a frame is tokens a second, half a kilobit for indices alone, excluding codebooks and metadata. It is decibels from the original by spectrum. Four tokens a frame cost four times as much and come to . As an unquantized reference, the true spectrum with an invented phase is away: a learned decoder can improve perceptual reconstruction; this phase-only reference is not a universal error floor. A language model over these tokens writes about sixty-two and a half symbols a second for one stream, not sixteen thousand.
5Language models over soundFoundations3 min
What does a language model write when its words are sound?
With a codec, sound becomes text, and the language models of AI, Built apply. AudioLM, from Zalán Borsos and colleagues in 2022, writes coarse tokens that capture content first, then the codec's fine tokens, each by a transformer. MusicLM, in 2023, does the same conditioned on text, through an embedding shared by music and words. MusicGen, from Jade Copet and colleagues that year, uses one transformer over EnCodec's four streams of tokens, each delayed against the last. They were trained on tens of thousands of hours of music. The model is the easy part; the data is not.
How does one transformer write four streams of tokens at once? MusicGen's answer is a delay. Each stream is shifted one frame later than the one above. At each step the model writes one token of every stream, but for different frames: the coarse stream for the newest frame, the finer ones for frames just behind it, whose coarser tokens are already written. Four streams cost one step a frame, not four.
Here is what the language model reads. A piano tune's spectrum, and the same with every frame replaced by its nearest entry in the first codebook: blockier, but the notes are all there. And the tokens themselves, one number a frame. In frames this tune used of the 256 entries.
Monochord's version: the pocket transformer of AI, Built, four layers, on the one-token codec's tokens of Part 65's chorale tunes played on the piano, about minutes. Its loss on tunes set aside falls and then turns, as Part 65's did, so it is kept as it was at step .
Hear a chorale tune the model never learnt from, through the codec, then its first four seconds continued by the model for six more. Both pass through the same codec, so codec reconstruction, phase synthesis and the model all affect the result.
After the prompt, listen for what survives. The training representation strongly favours piano-like spectral frames, since every token is a frame of piano; whether a tune survives, a line anyone would write down, is for your ear to judge. With forty minutes of data and under a million weights, this example may preserve texture more readily than long-range structure; the large models learnt structure from thousands of hours.
Does it copy? The longest run of its tokens that also occurs in its training tokens is frames, about seconds of piano, copied token for token. Exact runs are only a lower bound: a copied melody played a little differently gives different tokens. Large music models have been shown to reproduce training audio closely in some cases, and checking needs the training data. So Part 65's copying test matters more for sound, and is harder: it needs near matches, not exact ones.
6DiffusionFoundations3 min
Can a model draw by removing noise?
The third idea draws by removing noise. Take a real example and add a little noise, a hundred times over, until nothing is left but noise. At every step the example is a known mixture of the original and noise. Train a network that, shown a noisy example and how noisy it is, guesses the noise. Then generate: start from pure noise, and remove the guessed noise step by step back to the beginning. Jascha Sohl-Dickstein and colleagues proposed it in 2015, and Jonathan Ho and colleagues made it work in 2020; many image generators use related diffusion or flow methods.
Monochord's diffusion model draws something small: the profile of a bowed tone, the levels of its twenty-four harmonics, given only the pitch. It learnt from notes of the bowed-string model. Here is one profile being drawn, for the A above middle C: at step ninety-nine pure noise, then less and less, until at step nought a profile that falls away with the harmonics, as a string's does.
Hear steady tones at three pitches, first with profiles measured from the string model, then with profiles the diffusion model drew.
The drawn profiles are not exact matches to the finite training profiles: each differs from its nearest training profile by to decibels a harmonic on average. They are bright or dark as the string's are at those pitches. A steady profile is not an instrument, but the method that drew it scales.
Here are the profiles themselves, measured and drawn, at the three pitches. The drawn ones follow the measured ones' fall with the harmonic number, and their ups and downs, which come from where the bow touches the string, without copying any one of them.
For music, diffusion runs in a latent space, a compressed code of the sound learnt by an autoencoder. Stable Audio, from 2023, is latent diffusion conditioned on text and on timing, and makes minutes of audio. Every step refines the whole piece at once, with no left-to-right commitment, unlike a language model. Flow matching, from 2022, learns a vector field connecting distributions; sampling cost depends on the formulation, solver and model. This chapter's model, which draws a profile, and Stable Audio, which draws a song, share noise-based generative ideas but differ in architecture, representation, conditioning and task.
7Differentiable DSPFoundations3 min
Can a network learn to play a synthesizer?
The fourth idea keeps the synthesizer. DDSP, from Jesse Engel and colleagues at Google in 2020, learns only the synthesizer's controls. The synthesizer is the additive one of Parts 3 and 51: forty harmonics of the pitch, each with its own level, plus noise in sixteen bands. A network turns pitch and loudness, two hundred and fifty times a second, into those levels. It learns by comparing the synthesized and the real spectra at five resolutions; because every step of the synthesizer is differentiable, the error flows back to the network. The result is tiny, fast and controllable: pitch and loudness curves can drive it within practical sampling and synthesis limits.
Monochord's DDSP has weights, and learns from seconds of the bowed-string model's notes, a second at a time. The spectral loss falls steeply, then levels: most of a string's sound is a harmonic profile that depends on pitch and loudness, and that is just what the network can express.
Hear the Tune's opening on the string model, which the network never heard, then the network's resynthesis from that phrase's pitch and loudness alone.
By spectrum the resynthesis is decibels from the original, where noise of the same loudness would be . What it misses, if you listen for it, is in the attacks and in the bow's noise, which a few noise bands describe only roughly.
Here is what the network does over that phrase: the level of each of its forty harmonics, moment by moment. Each note starts bright, as the bow catches the string, and darkens as it settles: the brightness falls as the loudness grows, a correlation of minus nought point seven. Across pitches the profile changes little. These are the controls of a synthesizer, and they can be read, edited and driven by anything.
Because the network only sets a synthesizer's controls, it can be driven by curves it never saw. Hear it with a slow swell and a vibrato a semitone wide, then with a glide over an octave.
Neither gesture was in its training notes, each of which held one pitch at one bow. The synthesizer's harmonics follow the pitch exactly, providing an explicit pitch relationship; the predicted timbre can still fail outside the training range.
Drive it with anything, and it becomes an effect. Take a singer's pitch and loudness and drive the string with them: timbre transfer. The result keeps the singer's phrasing, vibrato and dynamics in the string's sound, as this part's Variation will let you hear. Real DDSP models learn violins, flutes and voices from minutes of recordings. And the same idea, controls taken from one performer and given to another's sound, is voice conversion: the next chapter's subject, and its problem.
8Singing and cloned voicesFoundations3 min
Whose voice is it, when a machine sings?
Machines have sung for a long time. The first singing synthesizers were rules, as Part 8's voice is: a source and formant filters. Then concatenation: Yamaha's Vocaloid, from 2004, joins recorded syllables of one singer, and its voice Hatsune Miku, in 2007, became a star in her own right. Then networks, from a score and lyrics to a spectrogram and through a vocoder to sound. Vocaloid's singers consented and were paid: the voice was licensed, like a sample library.
What a voice converter keeps and what it changes can be heard with Part 8's voices. Here is one performance of the Tune's first phrase, the same notes, timing and vibrato, sung by a soprano, an alto and a tenor.
The performance stays; the source and the vocal tract change, and with them who seems to be singing. In Part 8 each voice was a set of numbers we chose. An actual voice converter learns a representation from recordings; this demonstration instead switches explicit formant and source parameters, and that is where the trouble starts.
Voice conversion keeps a performance's content and timing and gives it another singer's timbre. A few minutes of someone's recordings can now be enough, and Part 64's separation supplies clean vocals from finished records. In 2023 a song with imitated voices of two famous singers spread widely before it was taken down. The singers had not consented, and the recordings the model learnt from belonged to someone. The goal is related to the last chapter's timbre transfer, though architectures and linguistic conditioning can differ; the difference is whose sound it is.
What does the law say? A person's vocal identity itself is generally distinct from copyright in performances, recordings and compositions; protection comes from rights of publicity and personality, which vary by place. Tennessee's ELVIS Act of 2024 added a person's voice to the likeness they control. Platforms label or remove imitations on request, and some artists license their voices to such models. What is settled is that consent and payment can be built in; what is not is the law across countries, which is changing as this is made.
9Judging generated soundPractice3 min
How close is a generated sound to the real thing?
How do you score generated sound without a listener? Embed many one-second chunks of real sound and of generated sound. Fit a Gaussian to each cloud of embeddings and measure how far apart they are: the distance between their means, plus a term for how differently they spread. That is the Fréchet Audio Distance of Kevin Kilgour and colleagues, from 2019, whose embedding was a network trained to recognize sounds. Here the embedding is Part 63's, sixty-two numbers, reduced to its eight main directions.
Here are the distances from the training strings. First a cheat: the training notes themselves, replayed, score , the best of all, as a copying generator would. Another phrase of the physical string model, the yardstick: . Then the generators: DDSP , the mel spectrogram turned back into sound , the sample-by-sample network , and white noise . The order, closest first: . The ordering may sound plausible here, but no listener study validates that agreement.
The distance has the faults of every single number. It is only as good as the embedding, and sees only what the embedding was trained to see. It is one number for a whole set, so it cannot say which sound failed, or how. And it rewards copying: replaying the exact reference collection gives zero distance by construction; replaying training data need not score perfectly against an independent reference set. So report it with a listening test, as in Part 58, a copying test, as in Part 65, and the prompts that were used.
Listening tests remain the reference. Part 58's MUSHRA test hides a reference and an anchor among the systems, and every one is rated against them, blind. A generator has no reference, so ask instead for preferences between pairs, or ratings of quality and of how well the music fits the prompt. The prompts matter: report them, and choose them before the systems are run, not after. And say who listened: musicians hear artifacts that others forgive.
10Watermarks and detectionPractice3 min
Can generated sound carry a label that cannot be heard?
A generator can label what it makes. A secret key seeds a random sequence of plus and minus ones, filtered to the middle of the spectrum. Add it far below the music, thirty-five decibels down. To detect it, correlate the audio with the key's sequence. Compare the score with what thirty keys never used give, and by chance it is about nought, give or take one; with the mark, large. This is spread spectrum, the method of the first audio watermarks; newer ones, like AudioSeal in 2024, learn their marks with a network.
Your turn. A bowed phrase, twice. One carries the watermark, thirty-five decibels below the music. Which one?
The first carried it. To the detector the difference is plain: a score of against . To the ear, at thirty-five decibels down under a bowed string, it may be hard to hear; this demonstration does not measure audibility thresholds.
What does it survive? A perceptual coder: through Part 58's coder at sixty-four kilobits, the score at thirty-five decibels down is . A shift of thirty-seven samples at sixteen kilohertz, about two point three milliseconds, sharply reduces the unaligned score, , unless the detector searches over shifts, . Played in a room, : the echoes smear it. Checked with ten wrong keys, the largest score is and the average : chance, with occasional high values. A threshold of five is an illustrative choice here, not a calibrated operational false-alarm guarantee. Real marks must also survive speed changes, re-recording through a room, and people trying to remove them, and the arms race is open.
Marks have limits. A mark only labels what its maker chose to mark, and open models can be run without one. Detectors trained to tell generated from recorded sound find the artifacts of today's codecs and vocoders. They are horses in the sense of Part 63: a new generator, or a generated file re-encoded, can fool them. So provenance is also being built from the other side: signing recordings when they are made, as some cameras now do under the C2PA standard.
11Frontier: data, consent and what is unsolvedResearch4 min
Whose music did the machines learn from?
The first frontier is data. MusicGen's authors say it was trained on twenty thousand hours of music licensed for the purpose. For several commercial song generators, the training data was not disclosed. Monochord's generators learnt only from sounds Monochord made, which is why they are small: this makes the provenance of these small demonstrations inspectable. What a model learnt from cannot be read off its weights. It must be disclosed, or found by tests like Part 65's.
The second is the courts, and everything here is dated. In June 2024 the major record labels sued Suno and Udio, two song generators, for training on their recordings without a licence. Later case status and licensing arrangements require checking the current court records and company announcements; the June 2024 filings alone do not establish today's status. Elsewhere, collecting societies have sued over lyrics and compositions, and courts are weighing fair use and exceptions for text and data mining. The outcome will decide who is paid when music is learnt from: Part 60's money, again.
What has changed for musicians already? Inside ordinary music software: separation, generated fills and stems, timbre transfer. For stock and background music, generated tracks now compete with commissioned ones. Streaming services have reported floods of generated uploads, and changed how they label them and pay for them. A common argument is that the work most at risk is the most routine and the work least at risk the most particular; it is an argument, not yet a measurement.
And what is unsolved. Form: generated songs drift; verses, choruses and returns are imitated rather than planned. Control: a sentence is a blunt instrument, and musicians want to edit a bar, a part or a mix, the stems of Part 64. Attribution: which training recordings made this output likely? And evaluation: no single metric captures everything listeners value.
A word about this part's own machines. Every one learnt only from sounds Monochord made, in minutes, on one computer. So each is small and each falls short: a sample-level network that overfit its small corpus, a token model that heard forty minutes of piano, a thirty-thousandth of MusicGen's twenty thousand hours. But every number they produced can be checked, because the training data is known, and so specified errors and matches against known training examples can be measured, while perceptual quality and attribution remain uncertain. The large systems do the same things at a scale of data that no outsider can inspect, which is the frontier's real problem.
A research problem to end on. Render a corpus whose every recording is known, with Monochord, in several styles. Train a token model and a diffusion model on it, at several sizes. For each output, estimate which training recordings it draws on, and evaluate with controlled training-set interventions; knowing the dataset alone does not provide ground-truth causal attribution for every output. Can attribution be made accurate enough to pay on? An answer would turn Part 60's royalty waterfall into something a generator could run.
Variation 66, recap and problemsAll tracks2 min
Every part ends by doing something to the Tune with what it built. Here the Tune is sung, then the singer's pitch and loudness drive the DDSP string, an octave up, and last the Tune's first phrase on the piano is continued by the token model, uncurated.
Row sixty-six of the ledger: the DDSP string decibels by spectrum from the string it learnt, and a few seconds of piano continued by a model trained on the synthetic piano corpus described earlier.
What did we find? Raw audio is long: sixteen thousand decisions a second, each, with mu-law, a choice among two hundred and fifty-six. A network that writes sample by sample can capture local detail while struggling with long-range structure in this small experiment. Spectrograms with vocoders, and codec tokens stage on stage, give compact representations. A language model over tokens learns texture before structure. Diffusion draws by removing noise, and DDSP learns the controls of a synthesizer. And generated sound is judged by distances, listeners and copying together, and marks label only what their makers chose to mark.
Five problems. One to compute, one to prove, one for your ears, one to build, and a research problem, marked with a star. Solutions are in this part's notes. Pause here.
Where does this come back? In research, where evaluation, listening tests and data are examined in turn, and in the concert at the end, where the generated Variations are labelled as such.
And in practice. Know the data a generator learnt from, and whether it was licensed. No one's voice without their consent. Label the output: mark it, and say so. And judge it three ways: by distance, by listeners, and by how much it copies.
The papers this part follows. The full list, with notes, is in the README.
Where it goes next. Evaluation, listening tests, leakage and data examined as research in Part 67; the generated Variations, labelled, in the concert of Part 68.
Key results
The part's results in one place, for revision.
Try it
Lab 66 · Generative audio's representations, computed
Compand samples with mu-law, quantize spectral frames into codec tokens stage on stage, compare sets of sounds by a Fréchet distance, and hide and find a watermark under music.
python -m videos.music.labs 66
needs numpy, scipy, matplotlib · download lab66.py ·
source on GitHuba quiet melody in 8 bits: equal steps, mu-law (signal to noise) 11 dB, 35 dB
codec, 1 token(s) a frame of 64 codewords: kbit/s, spectral distance 0.38, 7.0 dB
codec, 2 token(s) a frame of 64 codewords: kbit/s, spectral distance 0.75, 6.6 dB
codec, 3 token(s) a frame of 64 codewords: kbit/s, spectral distance 1.12, 6.5 dB
codec, 4 token(s) a frame of 64 codewords: kbit/s, spectral distance 1.50, 6.5 dB
no quantization at all (the phase alone invented) 6.2 dB
Fréchet distance: two sets of melodies; melodies against noise 2.9; 734.9
watermark -35 dB down: score marked; shifted (searched); unmarked; wrong key 24.3; 39.4; 0.7; 0.0
ear problem: the melody, then the codec at shuffled stages, then two phrases (one marked); which is which? (listen first) stages 2, 3, 4, 1; marked: second
Every generator needs a representation: mu-law makes a sample one of 256 classes; a codec makes a frame a few tokens, each stage cleaning up the last; a Fréchet distance compares whole sets of sounds; and a watermark rides under the music, found only with its key.
The code (103 lines; it asserts its own result)
"""Lab 66: generative audio's representations, computed: mu-law against plain 8-bit samples, a residual vector-quantizing
codec at one to four tokens a frame, a Fréchet distance between sets of sounds, and a spread-spectrum watermark with its
detector."""
import numpy as np
from videos.coursekit import labs
from explainer.music.monochord import Clip, concat
from explainer.music.monochord import genaudio as G
TITLE = "Generative audio's representations, computed"
GOAL = ("Compand samples with mu-law, quantize spectral frames into codec tokens stage on stage, compare sets of sounds "
"by a Fréchet distance, and hide and find a watermark under music.")
TASKS = [
"Change STAGES. How much does each extra codebook buy, in dB of spectral distance and in bits a second?",
"Change STRENGTH, the watermark's level. How quiet can it be and still be found through a time shift?",
"Change K, the codebook size. Is a bigger codebook or another stage the better use of eight more bits?",
]
STAGES = [1, 2, 3, 4]
STRENGTH = -35.0
K = 64
SR = G.SR16
def note(f, seconds, bright, rng):
t = np.arange(int(seconds * SR)) / SR
env = np.minimum(1, t / 0.03) * np.exp(-t * 2.5)
y = sum((bright ** (k - 1)) * np.sin(2 * np.pi * f * k * t + rng.uniform(0, 6.28)) for k in range(1, 12) if f * k < 7500)
return env * y
def melody(seed, n=16):
rng = np.random.default_rng(seed)
scale = [0, 2, 4, 5, 7, 9, 11, 12]
out = []
for _ in range(n):
m = 60 + scale[int(rng.integers(len(scale)))]
out.append(note(440 * 2 ** ((m - 69) / 12), float(rng.choice([0.25, 0.5])), float(rng.uniform(0.4, 0.8)), rng))
y = np.concatenate(out)
return y / np.max(np.abs(y)) * 0.8
def run(seed=0):
rng = np.random.default_rng(seed)
lab = labs.Lab()
y = melody(seed + 100)
quiet = y * 0.05
snr = lambda a: 10 * np.log10(np.sum(quiet ** 2) / np.sum((a - quiet) ** 2))
s_mu, s_lin = snr(G.unmulaw(G.mulaw(quiet))), snr(G.linear8(quiet))
lab.row("a quiet melody in 8 bits: equal steps, mu-law (signal to noise)", f"{s_lin:.0f} dB, {s_mu:.0f} dB")
assert s_mu > s_lin + 10
train = np.concatenate([melody(seed + k) for k in range(12)])
F = G.frames(train)
q = G.RVQ(max(STAGES), K, seed=seed).fit(F[rng.choice(len(F), min(len(F), 4000), replace=False)])
Ft = G.frames(y)
dists, clips = {}, [Clip(G.to48(y), 48000)]
for st in STAGES:
rec = G.from_frames(q.decode(q.encode(Ft, st)), len(y), iters=40)
dists[st] = G.spectral_distance(y, rec)
bits = st * np.log2(K) * SR / G.HOP / 1000
lab.row(f"codec, {st} token(s) a frame of {K} codewords: kbit/s, spectral distance", f"{bits:.2f}, {dists[st]:.1f} dB")
clips.append(Clip(G.to48(rec / (np.max(np.abs(rec)) + 1e-12) * 0.8), 48000))
assert dists[max(STAGES)] < dists[min(STAGES)]
gl = G.spectral_distance(y, G.from_frames(Ft, len(y), iters=40))
lab.row("no quantization at all (the phase alone invented)", f"{gl:.1f} dB")
def emb(ys):
"""Half-second chunks as 9 log band energies."""
rows = [np.log(np.mean(np.abs(G.stft(z[i:i + SR // 2])) ** 2, axis=1)[::32] + 1e-9)
for z in ys for i in range(0, len(z) - SR // 2, SR // 4)]
return np.vstack(rows)
real = emb([melody(seed + 200 + k) for k in range(4)])
other = emb([melody(seed + 300 + k) for k in range(4)])
noise = emb([rng.standard_normal(len(y)) * 0.2 for _ in range(4)])
d_same, d_noise = G.frechet(real, other), G.frechet(real, noise)
lab.row("Fréchet distance: two sets of melodies; melodies against noise", f"{d_same:.1f}; {d_noise:.1f}")
assert d_same < d_noise
key = 4321
m = G.watermark(y, key, strength_db=STRENGTH)
z = G.detect(m, key)
zs = G.detect(np.r_[np.zeros(25), m[:-25]], key, max_lag=40)
lab.row(f"watermark {STRENGTH:.0f} dB down: score marked; shifted (searched); unmarked; wrong key",
f"{z:.1f}; {zs:.1f}; {G.detect(y, key):.1f}; {G.detect(m, key + 1):.1f}")
if STRENGTH >= -40:
assert z > 5
order = list(rng.permutation(len(STAGES)))
marked_first = bool(rng.integers(2))
pair = [m, y] if marked_first else [y, m]
lab.audio = concat([clips[0]] + [clips[1 + i] for i in order] + [Clip(G.to48(p), 48000) for p in pair], gap=0.6)
lab.row("ear problem: the melody, then the codec at shuffled stages, then two phrases (one marked); which is which? (listen first)",
f"stages {', '.join(str(STAGES[i]) for i in order)}; marked: {'first' if marked_first else 'second'}")
fig, (ax1, ax2) = labs.figure(2)
ax1.plot(STAGES, [dists[s] for s in STAGES], "o-", color=labs.GOLD)
ax1.axhline(gl, color="0.6", ls="--")
ax1.set_xlabel("tokens a frame")
ax1.set_ylabel("spectral distance (dB)")
ax2.imshow(np.log(np.abs(G.stft(y)) + 1e-4), origin="lower", aspect="auto", cmap="magma")
ax2.set_xlabel("frame")
ax2.set_ylabel("bin")
lab.fig = fig
lab.note = ("Every generator needs a representation: mu-law makes a sample one of 256 classes; a codec makes a frame a few "
"tokens, each stage cleaning up the last; a Fréchet distance compares whole sets of sounds; and a watermark "
"rides under the music, found only with its key.")
return lab
Now change it
- Change STAGES. How much does each extra codebook buy, in dB of spectral distance and in bits a second?
- Change STRENGTH, the watermark's level. How quiet can it be and still be found through a time shift?
- Change K, the codebook size. Is a bigger codebook or another stage the better use of eight more bits?
Problems, with solutions
Try each problem before opening its solution.
-
Compute. A codec has 8 codebooks of 1,024 entries at 75 frames a second. What is its bit rate, and how many tokens is a three-minute song?
Solution
Each token is log₂ 1024 = 10 bits; 8 tokens a frame at 75 frames a second is 8 × 10 × 75 = 6,000 bit/s, 6 kbit/s (EnCodec's setting at 6 kbit/s is exactly this). A three-minute song is 180 × 75 = 13,500 frames, so 108,000 tokens: still long for a transformer, which is why the streams are delayed or modelled coarse first.
-
Prove. Show that if x_t = √ᾱ_t x₀ + √(1 − ᾱ_t) ε, predicting ε and predicting x₀ are equivalent.
Solution
Given x_t and t, the relation is invertible in either unknown: x₀ = (x_t − √(1 − ᾱ_t) ε) / √ᾱ_t and ε = (x_t − √ᾱ_t x₀) / √(1 − ᾱ_t). A network that outputs ε̂ thereby outputs x̂₀, and conversely; their squared errors differ by the factor ᾱ_t / (1 − ᾱ_t), which is why the two parametrizations weight the steps differently in training while describing the same denoiser.
-
Ear. The lab plays a codec at 1 to 4 stages and marked and unmarked phrases; order and spot them, then check.
Solution
The lab prints the order and which phrase was marked. On its synthetic melodies the stages differ by tenths of a decibel, as in the film, and the mark at −35 dB is found by the detector with a score above 20 while hard to hear.
-
Build. Give the DDSP synthesizer a learnt reverb (Part 49) and train it on the string in a room.
Where to look. Append to
_torch_syntha convolution with a learnable impulse response (a second or so of free parameters, initialized as decaying noise); render the training notes through Part 49's room; train as before and compare the spectral distance with and without the reverb, and the learnt response with the room's. -
★ Can training-data attribution for generated audio be made accurate enough to pay on?
Where the frontier is. Render a corpus whose every recording is known, train token and diffusion models of several sizes, and for each output estimate which recordings it draws on (by influence functions, by embedding similarity, by retraining without candidates); score the estimates against the truth, which here is known.
Notes and sources
Sources
- A. van den Oord et al., "WaveNet: a generative model for raw audio" (2016); P. Dhariwal et al., "Jukebox" (2020).
- R. Kumar et al., "MelGAN" (NeurIPS, 2019); J. Kong, J. Kim and J. Bae, "HiFi-GAN" (NeurIPS, 2020).
- N. Zeghidour et al., "SoundStream: an end-to-end neural audio codec" (2021); A. Défossez et al., "High fidelity neural audio compression" (EnCodec, 2022).
- Z. Borsos et al., "AudioLM" (2022); A. Agostinelli et al., "MusicLM" (2023); J. Copet et al., "Simple and controllable music generation" (MusicGen, NeurIPS, 2023).
- J. Sohl-Dickstein et al., "Deep unsupervised learning using nonequilibrium thermodynamics" (ICML, 2015); J. Ho, A. Jain and P. Abbeel, "Denoising diffusion probabilistic models" (NeurIPS, 2020); Z. Evans et al., "Fast timing-conditioned latent audio diffusion" (Stable Audio, 2024); Y. Lipman et al., "Flow matching for generative modeling" (2022).
- J. Engel, L. Hantrakul, C. Gu and A. Roberts, "DDSP: differentiable digital signal processing" (ICLR, 2020).
- K. Kilgour et al., "Fréchet Audio Distance" (Interspeech, 2019); R. San Roman et al., "Proactive detection of voice cloning with localized watermarking" (AudioSeal, 2024).
Review qualifications: codec frames advance every 16 ms (62.5 Hz), not every sixteenth of a second. Exact matches and FAD-style distances are reference-dependent checks, not proofs of originality, causal attribution or perceptual quality. Current lawsuit and licensing status requires checking dated primary records. The formant-voice demonstration switches explicit synthesis parameters rather than implementing a trained voice converter.
Token payload rates count code indices only and exclude codebooks and metadata; the unquantized-spectrum row is a reconstruction reference, not a zero-rate codec.
About this partfrom its README
Part 66 of a sixty-eight-part course in music (see the series plan and
the syllabus), the last part of Act XI, Listening Machines. In 2016 a network wrote sound one sample at
a time, sixteen thousand decisions a second, and its piano noodled nowhere; eight years later a line of text returned a
finished song with a singer, and the record labels went to court. This part explains the ideas that closed the gap and
builds the smallest honest version of each: a network that writes samples, spectrograms and their way back to sound, a
codec's tokens and a language model over them, a diffusion model, a network that plays a synthesizer (DDSP), and the means
of judging and marking what such machines make. The tools are Monochord's (explainer/music/monochord/genaudio.py, with
AI, Built's pocket transformer); every training sound was made by Monochord, so what each model learnt from is known
exactly. Results are reported as they are, including the failures.
- Sixteen thousand decisions a second. An ear question (Part 9's bowed string and a DDSP network's copy from its pitch and loudness: which is the network? the first, 6.7 dB from the string by spectrum); from WaveNet (2016) through Jukebox, MusicLM and MusicGen to the lawsuits of 2024; the plan.
- 1. Why raw audio is hard. A second at three magnifications; the numbers (a CD second is 1.4 million bits; a song three million decisions); mu-law; equal steps against mu-law on a quiet phrase, heard (18 against 37 dB).
- 2. One sample at a time. WaveNet; Monochord's network over the last 256 samples, trained on 49 s of the string model (about 4.3 bits a sample on its training notes, 8.4 on a phrase it never heard: worse than a blind guess on that held-out phrase; the loss gap alone does not prove literal memorization); half a second continued for one second, heard (278 s of computing); the lesson: split structure from detail.
- 3. Spectrograms and vocoders. A phrase as a 64-band mel spectrogram; rebuilt by pseudo-inverse and Griffin-Lim, heard (15.4 dB away; the true spectrum with an invented phase, 3.8); 16, 64 and 256 bands, heard (20.6, 15.4 and 8.3 dB); neural vocoders.
- 4. Tokens from a codec. Vector quantization; SoundStream and EnCodec; Monochord's residual vector quantizer on log spectra (256-entry codebooks, 62.5 frames a second); an ear question (one, two and four tokens a frame, in order: they differ by only 0.2 dB, since one codebook holds most of one instrument's frames); bits against fidelity (0.5 kbit/s: 4.3 dB; 2 kbit/s: 4.1; the phase floor 3.7).
- 5. Language models over sound. AudioLM, MusicLM, MusicGen; MusicGen's delay pattern; a tune as tokens (44 of 256 codewords in 240 frames); the pocket transformer (845,440 weights) on 152,965 tokens of 91 piano chorale tunes (about 41 minutes), stopped at step 850 on tunes set aside; a tune it never learnt continued for six seconds, heard; its longest run copied token for token, 64 frames (one second).
- 6. Diffusion. Adding and removing noise; a diffusion model of a bowed tone's 24-harmonic profile, conditioned on pitch, learnt from 300 notes; a profile drawn step by step; measured and drawn tones at three pitches, heard (each drawn profile 3.7 to 4.9 dB a harmonic from its nearest training profile); latent diffusion and flow matching.
- 7. Differentiable DSP. Engel et al. (2020); Monochord's DDSP (24,249 weights: 40 harmonics and 16 noise bands set 250 times a second), trained on the string model by a five-resolution spectral loss; the Tune's opening, never heard, resynthesized (6.0 dB away, against 28.8 for noise), heard; the controls it sets (each note starts bright and darkens: brightness against loudness, r = −0.73); a vibrato and a glide it never saw, heard; timbre transfer.
- 8. Singing and cloned voices. Singing synthesis from rules to Vocaloid; one performance in three of Part 8's voices, heard; voice conversion and cloning; the law, for now (dated).
- 9. Judging generated sound. The Fréchet distance (FAD); against the training strings: the training notes replayed 6.5 (a copier scores best), another real phrase 15.7, DDSP 20.0, mel and Griffin-Lim 41.1, the sample-level network 44.9, white noise 203; what the distance misses; listening tests for generators.
- 10. Watermarks and detection. A spread-spectrum mark 35 dB down, standardized against 30 unused keys; an ear question (which carries it? the first: 31 against −0.8); through Part 58's coder 25.6; shifted 37 samples at 16 kHz (2.3 ms), −0.4, unless the detector searches shifts (73); in a room 1.1; ten wrong keys at most 3.4 (mean 0.7); detectors and provenance.
- 11. Frontier: data, consent and what is unsolved. Training data; the courts (dated); what changed for musicians; form, control, attribution and evaluation; the smallest honest versions; ★ research problem: can training-data attribution for generated audio be made accurate enough to pay on?
- Variation 66, recap and problems. The Tune sung by Part 8's alto, its pitch and loudness driving the DDSP string an octave up, and its first phrase on the piano continued for five seconds by the token model; the ledger; what we found; five problems; where it comes back; in practice; references; Part 67.
What is computed and built
python -m videos.music.music66.compute (an hour or so on a busy machine: five networks train, and the sample-level one
writes its second slowly) fills .cache/music66/.
| Item | What it computes | Checked against |
|---|---|---|
corpus, rates, zoom |
the string and piano corpora; mu-law against equal steps; a second magnified | by construction (tests) |
ar |
a sample-level network: bits per sample, a continuation | a phrase it never heard (tests) |
vocoder, melbands |
mel spectrograms back to sound | the original phrase (tests) |
codec, tokpic, tokenlm |
residual VQ at 1, 2, 4 stages; a transformer over tokens; copying | held-out tunes; the training tokens (tests) |
diffusion |
a diffusion model of harmonic profiles | the nearest training profile (tests) |
ddsp, vibrato, hook |
DDSP trained on the string model; resynthesis; new controls | a phrase it never heard (tests) |
fad |
Fréchet distances in Part 63's embedding | the training strings (tests) |
watermark |
marks at −25 and −35 dB through a coder, a shift and a room; wrong keys | unmarked audio and unused keys (tests) |
voices, tune66 |
one performance in three voices; Variation 66 | — |
Monochord's tools are held in tests/music/test_genaudio.py; this part's claims and clips in tests/music/test_music66.py.
Sounds. Part 9's bowed string (training notes at random pitches, lengths and levels; the Tune held out), Part 38's piano playing Part 65's chorale tunes (split by hymn tune), Part 8's voices. Everything is generated at 16 kHz and resampled to 48 kHz for the film.
What the models are, and are not. The sample-level network is two dense layers over 256 samples, not WaveNet's dilated stack; it generalizes poorly on the held-out phrase. The codec has no learnt encoder or decoder: k-means codebooks on log spectra and Griffin-Lim's phase, so reconstruction error includes both phase estimation and spectral quantization; the phase-only reference is not a universal bound. The token model has one codebook stream and forty minutes of one instrument. The diffusion model draws a 24-number profile, not audio. The DDSP model learns one synthetic string whose timbre does not depend on loudness, and has no reverb. The Fréchet distance uses Part 63's hand-made embedding reduced to 8 directions, from few chunks, so its values are rough. The watermark is a textbook spread-spectrum mark; it does not survive a room, and nothing here was tested against an attacker.
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- Hook: an ear question (the string or its DDSP copy?); from WaveNet to the lawsuits; the plan.
- Why raw audio is hard: a second magnified; the numbers; mu-law, heard.
- One sample at a time: WaveNet; a sample-level network that memorized; a continuation, heard; the lesson.
- Spectrograms and vocoders: a mel spectrogram; rebuilt, heard; how many bands, heard; vocoders.
- Tokens from a codec: vector quantization; residual stages; an ear question (how many tokens?); bits against fidelity.
- Language models over sound: AudioLM, MusicLM, MusicGen; the delay pattern; tokens as a picture; training; a continuation, heard; copying.
- Diffusion: adding and removing noise; a profile drawn; measured and drawn tones, heard; the profiles; latent diffusion.
- Differentiable DSP: the idea; training; a phrase it never heard, heard; its controls; new controls, heard; timbre transfer.
- Singing and cloned voices: singing synthesis; one performance in three voices, heard; cloning; the law (dated).
- Judging generated sound: the Fréchet distance; the table; what it misses; listening tests.
- Watermarks and detection: spread spectrum; an ear question (which is marked?); what the mark survives; detection.
- Frontier: data; the courts (dated); musicians; the unsolved; the smallest honest versions; the research problem.
- Variation 66: sung, re-rendered by DDSP, continued by the token model. Outro: problems, payoffs.
Covers: why raw audio is hard; autoregression on samples; spectrograms and vocoders; discrete tokens and
neural codecs; language models over tokens; diffusion and flow models in a latent space; differentiable DSP;
singing synthesis and voice cloning; evaluation; watermarking and detection; data, consent and what is unsolved.
Built and computed: monochord/genaudio.py: mu-law (37 dB against 18 for equal steps on a quiet phrase); a
sample-level network (8.4 bits a sample on new audio: it memorized); mel and Griffin-Lim (15.4 dB at 64 bands, 8.3
at 256); a residual VQ codec (one to four tokens a frame within 0.2 dB, the phase floor 3.7); a pocket transformer
over codec tokens of 41 minutes of piano (longest copy one second); a diffusion model of harmonic profiles; DDSP on
the string model (6.0 dB away on a phrase it never heard, 24,249 weights); Fréchet distances (the training notes
replayed score best); a spread-spectrum watermark (31 at −35 dB, 25.6 through a coder, lost in a room).
Variation 66: the Tune sung, re-rendered as a string by the DDSP model, and continued by the token model.
Frontier: the frontier is the subject: swept at the writing date.
Reading: van den Oord et al. (2016); Engel et al. (2020); Zeghidour et al. (2021); Agostinelli et al. (2023);
Copet et al. (2023).
Build the film
python -m videos.music.music66.compute # the part's numbers, into .cache/music66
python tools/build.py music66 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py music66 Hook # one chapter, silent, with a contact sheet
Scenes: videos/music/music66. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
python -m videos.music.music66.compute # numbers and sounds (the networks train)
EXPLAINER_TTS=silent python tools/build.py music66 -q l --fps 15 # a silent-narration preview, with the sounds
python tools/qa_sound.py music66 --sync # the sound gates
python tools/dead_air.py renders/music66_480p.mp4 --sound music66 # no empty screen; no sound over a still one
python tools/lecture_length.py music66 # 30 to 60 minutes, listening included
python tools/build.py music66 # 1080p30, narrated
python -m pytest -q tests/music # Monochord against its references; this part's claims and clips
python -m videos.music.labs 66 # the lab (writes a figure and a short WAV)