Source Separation
How can a machine pull one instrument out of a finished mix, and how do we know how well it did?
An ear question: a voice and a piano on one track, then the voice twice; the first was separated, 12 dB from the truth; a home cassette lifted apart decades later. The mixing model and the assumptions separation needs; Part 56's session as the test set, its four stems heard alone and mixed. Stereo: left minus right, 11 dB quieter, the centred voice, bass and drums gone, heard; a panning index per bin picks out the piano roughly (2.7 dB); the session's energy by index. ICA: the session as a cloud of samples squared up; the voice is the most non-Gaussian direction (kurtosis 1.61 against the microphones' 1.34 and 0.82); perfect dry, lost in a room, heard. Median filtering: lines and stripes, the harmonic mask, the split heard (tonal 7.8 dB, drums 1.0), long filters better (10.1 and 3.4), heard. Supervised NMF: the voice's combs and the drums' smears; stems from 5.2 to 8.5 dB; templates per source (gains flatten after six). Oracle masks as pictures and as ceilings (vocals: NMF 7.7, binary 8.3, ratio 9.3, with true phase 12.7; for drums the binary mask wins), heard. Phase: Griffin-Lim heard, its inconsistency falling to -20 dB while its SDR stays near -3; an ear question on the phase gap; waveform separators. A small vocal-mask network trained on the middle phrases transposed: 6.9 dB, below NMF; trained on stretches that repeat the test, 8.5: what a leak is worth. Measuring: SDR, SI-SDR, BSS Eval; an ear question on two estimates at exactly 8.0 dB, one leaking and one gargling; a perfect estimate half as loud, upside down, dull and a millisecond late (-0.6 dB), heard. Uses, an ear question on a remix from separated stems (13.7 dB from the true remix), rights. Frontier: generative and query-based separation, better metrics. Variation 64: the Tune a cappella and as karaoke, separated and true.
What you need. Part 2 for spectra; Part 45 for the auditory scene; Part 54 for panning; Part 56 for the session; Part 61 for NMF. The short-time Fourier transform, whitening and kurtosis, median filters, multiplicative updates, least squares, gradient descent.
- Ideas, mathematics and history
- the cocktail party, panning and ICA, harmonic–percussive separation, masks and oracles, the phase problem, U-Nets and Demucs
- What we build, compute and hear
- separators scored against our own multitracks; a mashup from separated stems
What you will be able to do
Foundations
- Hear stems alone and mixed, centre cancellation, ICA dry and in a room, and the harmonic and percussive halves.
- Hear separated voices against the oracles, the phase gap, and two estimates with equal SDR and different faults.
- Explain why one channel needs assumptions, and why a mask's ceiling is set by phase.
Full course
- Separate by panning, FastICA, median filtering, supervised NMF and a mask network; score each by SDR and SI-SDR.
- Compute the ideal binary and ratio masks and the true-phase bound for a mixture whose stems are known.
- Recover a phase from a magnitude by Griffin-Lim, and measure its consistency and its error.
Research
- Test which measures predict listeners' ratings of separations, including generative ones that invent.
Practice
- Keep test material out of training, report SDR with the oracle bounds beside it, and listen as well as measure.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Foundations 24 min · Full course 29 min · Research 31 min · Practice 29 min.
- 0Un-baking a cakeFoundations2 min
- 1The mixing modelFoundations2 min
- 2Where things are pannedFoundations2 min
- 3Independent componentsFoundations3 min
- 4Harmonic and percussiveFoundations2 min
- 5Factorization, againFoundations3 min
- 6Masks and oracle referencesFoundations2 min
- 7The phase problemFoundations3 min
- 8Networks that separatePractice2 min
- 9Measuring separationFoundations3 min
- 10What separation is forPractice2 min
- 11Frontier: generative and query-based separationResearch3 min
- Variation 64, 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.
Un-baking a cakeFoundations2 min
In 2023 software separated the voice of John Lennon from a cassette he had recorded at home. Try a smaller case first. A voice and a piano synthesized separately and summed onto one track. Then the voice twice: once as synthesized on its own, once separated from the mix by a machine. Which is the separated one?
The first was separated: listen for a faint ghost of the piano and a little smearing. The second was the voice as recorded alone. By the measure of Chapter 9, the separation is decibels from the truth.
The question has a famous answer. Around 1977 John Lennon recorded a song at home on cassette, voice and piano on one track. In the 1990s the surviving Beatles tried to finish it and gave up: the piano and the hum could not be taken away from the voice. In 2023, software built for a documentary separated the voice, and the song, Now and Then, was released. Separation is un-baking a cake: the mix adds everything together, and addition forgets. Monochord owns the ingredients of its cakes, so this part can say exactly how well each method does.
Here is the plan. The mixing model, and what it takes to undo it. Separating by where sounds are panned, and by independence. Harmonic against percussive, and factorization again. Masks and source-informed reference estimates. The phase problem, and networks that separate. And how separation is measured, and what it is for.
1The mixing modelFoundations2 min
What exactly has to be undone?
What has to be undone? In the simplest model, the sources are added on one channel: one equation, several unknowns. With several channels, each source can be panned: each channel is a different weighted sum, instantaneous mixing. And in a real recording each source reaches each microphone through a room, so it arrives smeared in time: convolutive mixing. Part 56 built all three kinds of mix; now we run them backwards.
With one channel and two sources there are infinitely many pairs of signals that add up to the same mixture. So every method assumes something about the sources: where they are panned, that they are independent, what they sound like. Assumptions help when they match the actual sources and mixing process. A network assumes what its training data showed it, one set of learned statistical assumptions.
The test is our own. Part 56's synthetic session, whose every track Monochord generated and mixed. Four stems, as the field's benchmark has them: vocals, bass, drums, and everything else. The separators learn from the session's later phrases and are tested on its first two. The benchmark itself, MUSDB18 from 2017, has a hundred and fifty real songs with their stems. We can compute waveform errors against known references; numerical approximations and metric limitations still apply: we own the ingredients of the cake.
Before separating anything, meet the four stems, each alone for four seconds, then mixed. Every separator in this part will be asked to get from the last box back to the first four.
The voice carries about a third of the mix's energy, per cent; the bass, drums and the piano and guitar a fifth or a quarter each. Easy to tell apart by ear, and, as we shall see, hard by machine.
2Where things are pannedFoundations2 min
Can two channels be played against each other?
Stereo gives a first handle. Each source is panned by an angle: some of it in the left channel, some in the right. In this gain-only panning model, a centred source is identical in both. So subtract the channels, and it vanishes exactly: the old trick of karaoke machines, which removed a centred singer. It also removes everything else in the centre: the bass and the kick drum go with the voice.
Hear the session in stereo; then left minus right; then only the time-frequency bins panned where the piano is. Headphones help.
Left minus right keeps only what is panned: the piano and guitar, with the voice, bass and drums gone. The piano's bins hold mostly piano, with traces of whatever shared its frequencies.
The idea generalizes. In every time-frequency bin, compute a panning index, from minus one for hard right to plus one for hard left. A source panned to one place lights the bins with that index, as Carlos Avendano showed in 2003. Selecting the piano's bins gives the piano at decibels, by the measure of Chapter 9: where piano and guitar share a bin, its index falls between them. And it fails for sources panned to the same place, above all the centre, where most voices are.
Here is the session's panning, bin by bin: how much energy sits at each panning index. Most of it is in the centre, where the voice, bass, kick and snare are. The rest spreads into broad shoulders, toward the piano on the left and the guitar and hi-hat on the right. They are broad because most bins hold more than one source, and interference can complicate a shared bin's index. So panning selects the piano only roughly, and the tall peak in the middle holds four sources it cannot tell apart.
3Independent componentsFoundations3 min
Can a machine separate two sources without knowing what they are?
With two channels there is a purely statistical trick. Two microphones and two sources, each microphone hearing a different mix. If the sources are independent, look for the un-mixing that makes the outputs as independent as possible. Under identifiable instantaneous mixing and independence assumptions, non-Gaussian contrasts can help recover sources; the central limit theorem motivates this, without making every two-source sum more Gaussian in every metric. Aapo Hyvärinen's FastICA whitens the data, then rotates it until each output is as non-Gaussian as it can be. No source templates, but strong independence and mixing assumptions: blind source separation.
Here is what it sees, sample by sample. Two independent sources: a scatter aligned with the axes. Mixed, the scatter is sheared and rotated. ICA finds the transformation that squares it up again; it cannot know the sources' order or loudness, but it can recover their shapes under those assumptions.
Now real music: the session's voice and its piano and guitar, mixed into two channels. Each dot is one sample, the left microphone across and the right one up: a slanted, star-shaped cloud, because music is mostly quiet with occasional loud moments. ICA's outputs turn the star square to the axes: where one source is loud, the other is usually near zero, so its arms lie along the axes.
Why does this work? Measure how far a signal is from Gaussian by its excess kurtosis: nought for Gaussian noise, large for a signal that is mostly quiet with loud peaks. The voice scores , the piano and guitar ; the two microphones, being mixtures, score less, and : the central limit theorem at work. After whitening, try every direction through the cloud. The most non-Gaussian direction is the voice itself; that is the direction FastICA climbs to.
Hear the voice as ICA recovers it from a dry two-channel mix of voice and piano, then from the same mix played in a room.
Dry, it is essentially perfect. In this simulated room the instantaneous method performs poorly: each source reaches each microphone through echoes, a convolution, and a single un-mixing matrix cannot undo that. Convolutive ICA works frequency by frequency, and must then decide which piece belongs to which source.
4Harmonic and percussiveFoundations2 min
Can a picture's lines be told from its stripes?
On one channel, look at the picture. In a spectrogram a sustained note is a horizontal line, steady in frequency and long in time. A drum hit is a vertical stripe, brief in time and broad in frequency. A median filter along time keeps the lines and erases the stripes; along frequency, the opposite. Compare the two in each bin and share the bin between them, as Derry FitzGerald proposed in 2010. One channel, no training, a few lines of code.
Here is the harmonic mask for the session: bright where a bin is mostly harmonic. The horizontal lines are the voice, bass, piano and guitar; the dark vertical stripes are the drum hits.
Hear the two halves. The harmonic half is the band without its drums, decibels from the true tonal stems. The percussive half is less clean, decibels: the attacks of the piano and guitar count as percussion too, and the hi-hat's hiss is neither line nor stripe. A good first step for remixing, and for Part 62's beat tracker, which wants the stripes.
The method has two knobs: how long the median filters are, and how sharply the masks decide. Short filters cannot tell a line from a stripe; longer ones can. On this session both halves keep improving up to sixty-three frames, the tonal stems to decibels and the drums to , because its notes are long. Sharper masks, power two, help a little. The best settings depend on the music, which is why such knobs are tuned on examples.
Hear the percussive half with the shortest filters, then the longest. With short filters, the voice and the piano bleed into the drums: a five-frame median cannot tell a note from a hit. With long ones, the drums are drier and the tones mostly gone, though the hi-hat's hiss and the piano's attacks remain.
5Factorization, againFoundations3 min
Can Part 61's templates pull a mix apart?
Factorization works for sources as well as notes. Part 61 used it to find notes; here each source gets its own set of templates. Learn twelve templates from each stem's recordings in other phrases: the voice's vowels, the drums' hits. Fit the mixture with all forty-eight templates fixed; each source is the part of the fit that its own templates explain. Turn each part into its share of every bin, a soft mask, and apply it to the mixture. It is supervised: it needs examples of each source, but not of this mixture.
Here is what the templates learnt. The voice's are combs: a few strong harmonics, spaced by the pitch of a note, with the bright bands of its vowels. The drums' are smears: the kick's low thump, the snare's broad noise, the hi-hat's hiss at the top. The mixture is fitted as a sum of these columns, and each source keeps what its own columns explain.
Here is how close each separated stem comes to the truth, in decibels of signal to distortion: nought decibels would mean as much error as signal. The drums come out best, at decibels, with the vocals close behind at . The bass and the piano and guitar come out worst, near : they share the low and middle frequencies, and the piano and guitar change their spectra from chord to chord, so a few templates describe them only roughly.
How many templates should each source get? With one, each source is a single fixed spectrum, and the vocals score decibels. Three templates give , six . Then the curve flattens: from six to twenty-four, four times the work, the vocals gain only of a decibel. Pushed further, a source's templates start to describe the other sources too. The number is a compromise, tuned on examples.
Hear the vocal stem as the factorization separates it, decibels from the truth.
The voice is there, with traces of the others: the guitar where it shares a vowel's formants, the hi-hat's hiss in the consonants.
6Masks and oracle referencesFoundations2 min
What do source-informed masks tell us?
Step back. Nearly every method so far is a mask: a number between nought and one for every bin of the spectrogram, multiplied into the mixture. If we knew the true sources, we could choose the best masks. The ideal binary mask gives each bin to the loudest source; the ideal ratio mask shares each bin in proportion. They need the answer, so they are not methods; they are source-informed reference masks, not proven optima for waveform SDR; phase-sensitive or complex masks can perform differently.
Here are the vocals' two ideal masks beside the mixture. The binary mask is black and white: each bin is the voice's or not. The ratio mask has shades of grey, sharing each bin. Both trace the voice's harmonics, and both need the true vocals to draw.
Here are the reference scores, stem by stem. NMF, from the last chapter. The ideal binary mask: NMF is already close to it, and for the bass and the piano and guitar a little above it. The ideal ratio mask is higher for all but the drums, whose hits so dominate their bins that giving each bin away wins. NMF's vocals are only decibels below this reference. The last column gives the ratio mask the true phase of each source, which these real-valued nonnegative masks cannot supply, and it is decibels higher again for the vocals: the biggest gap of all, and the next chapter's subject.
Hear the vocals through the ideal binary mask, the ideal ratio mask, and as recorded.
The binary mask switches bins fully on and off, and the holes it leaves gargle: musical noise. The ratio mask is smoother, and close to the truth.
7The phase problemFoundations3 min
Is a spectrogram's magnitude enough to rebuild a sound?
Masks have a blind spot. A mask scales magnitudes and keeps the mixture's phase in every bin. Where sources overlap, the mixture's phase is neither source's, and a nonnegative real-valued mask cannot correct that phase error; complex masks can change phase. Could the phase be rebuilt from the magnitude? Daniel Griffin and Jae Lim's method of 1984 goes back and forth between a spectrogram and a signal, keeping the magnitude each time. It seeks a more consistent spectrogram, without guaranteeing the true phase or a global optimum.
Here is the vocals' true magnitude, first with a phase invented by Griffin and Lim's method, then with the mixture's phase.
Griffin and Lim's sounds a little phasey and hollow, and by the waveform measure it is far from the truth, decibels: its phases are approximately consistent but not the voice's own. The mixture's phase, wrong only where the sources overlap, scores . Phase constrains these mixture-phase masks.
Watch Griffin and Lim's method work. Iteration by iteration, the signal's spectrogram comes closer to the target magnitude: from decibels off to after a hundred rounds. And its distance from the true vocals stays poor in this run; the SDR stays near minus three. It finds a signal with the right spectrogram, and there are many, nearly all of them different from the voice sample by sample.
Your turn. How much does phase matter to the ear? Here are the vocals through the ideal ratio mask twice, once with the mixture's phase and once with the voice's own. Which had the voice's own?
The second had the voice's own phase. By SDR, decibels, then . Listen again where the band and the voice share a harmonic: that is where the two differ. Whether three decibels of SDR sound like much is a question for the ear, not the formula, and Chapter 9 takes it up.
One answer is to avoid the spectrogram altogether. Separate in the waveform itself, so phase is represented implicitly in the samples. Wave-U-Net in 2018 and Demucs, from Alexandre Défossez and colleagues in 2019, are networks from samples to samples. Later Demucs versions combine both, a spectrogram branch and a waveform branch with a transformer between them. On the MUSDB18 benchmark, vocal separation improved from a few decibels around 2015 to about nine or more; check the latest.
8Networks that separatePractice2 min
Can a network learn what a voice looks like in a mix?
Monochord's network is small. Its input is the mixture's log spectrogram, five frames at a time. Its output is a clipped vocal-to-mixture magnitude mask for the middle frame, up to nine kilohertz. Two hidden layers of five hundred and twelve units: roughly one and a half million trainable parameters. It is trained on the session's middle phrases, transposed five ways, and tested on the first two, whose melody it never heard. Not on the last two: the Tune ends by repeating its opening, and training there would be training on the test. A toy beside Demucs: the same idea, with a tiny fraction of the data.
Training lowers the error of its masks, epoch by epoch, on the stretches it learns from.
Hear the vocals as the network separates them, then as recorded. On phrases it never heard, it reaches decibels: a recognizable voice, with the band's traces around it, and the top of its range gone, since the network sees nothing above nine kilohertz.
All together, for the vocals. The network trails the factorization, which learnt from the same phrases: decibels against . Both sit below these source-informed reference scores, which are not universal bounds. A network is only as good as its data, and this one learnt from a few seconds of one band, transposed; Demucs learnt from the hundred training songs of the MUSDB18 benchmark, and later versions from hundreds more.
A confession. The first version of this network was trained on four stretches of the session, two of which contained the Tune's last phrases, which repeat its first, and one the second test phrase itself. Honest, it scores . With the leak, , enough to beat the factorization and to tell a better story. The learning code could execute correctly while the evaluation design leaked test content; the test simply was not new. Part 63's horse, again: check what the test set shares with the training set before believing a score.
9Measuring separationFoundations3 min
Does one number say how good a separation sounds?
Every number so far has been the signal-to-distortion ratio. The true source's energy against the energy of the error, in decibels. Squared sample errors are accumulated without a perceptual weighting: another source leaking in, artifacts, even a change of level. The scale-invariant version first finds the best gain, so that a quieter but otherwise perfect estimate is not penalized. And the BSS Eval toolkit of 2006 splits the error into interference, artifacts and noise.
Your turn. Two separations of the same voice, with exactly the same SDR. Which would you rather hear?
Both score decibels. The first lets the piano and guitar through, quietly, and still sounds like music; the second has bins switched off at random and gargles. The first may sound preferable; no listener preference study is reported here. One number cannot say which error is worse.
Take a perfect estimate and change it in ways whose perceptual effects vary. Half as loud: SDR gives decibels, and the scale-invariant version says perfect. Upside down, whose polarity reversal alone is often hard to hear, though audibility is signal- and playback-dependent: SDR says minus . Dull, with everything above two kilohertz removed: decibels, nearly perfect, because so little of a voice's energy is up there. And one millisecond late, typically hard to notice in isolated playback: decibels, worse than nothing at all.
Hear them: the vocals as recorded, the dull ones, and the late ones. The dull voice is the one you can hear is different, if you listen closely, and it scores best. The late one sounds identical to the original, and scores worst. The scale-invariant measure fixes gain, not time or timbre.
So the numbers miss things. SDR ignores perception: masking, which errors are audible, and which are merely annoying. Listening tests, like the MUSHRA tests of Part 58, remain the reference, and they are slow and costly. Perceptual measures, and networks trained on listening tests, are being built. Meanwhile, report SDR, its scale-invariant cousin and a listening test, with the oracle reference scores beside them.
10What separation is forPractice2 min
Who needs a mix un-mixed? Restorers: a voice lifted from a demo cassette, old mono recordings remixed in stereo. Karaoke and practice: the voice removed, or the drums, so you can play along. Remixers and samplers, taking a single stem from a finished record, though Part 60's licences still apply. Upmixing: stereo spread to surround and to Part 55's immersive formats. And analysis: cleaner input for Part 61's transcribers and Part 62's chord recognizers.
Your turn. A remix needs less than you might think. Hear the session as mixed, then two remixes with the vocals six decibels up and the drums six down. One was made from the network's vocals and the median filter's drums; the other from the true stems. Which was separated?
The first remix was the separated one. The two are close: decibels apart by SDR, much closer than either is to the original mix. A remix adds the stems back together, so whatever one stem wrongly took from another is mostly returned. Turning a voice up or down is far easier than lifting it out alone: a separator can be good enough for a remix long before it is good enough for an a cappella.
Separation also raises questions. A separated stem is still a copy of the recording, and the master's rights travel with it. The separated vocal of a famous singer is the raw material of voice cloning, the subject of Part 66. Apps now separate on a phone, in real time: some recordings can now yield useful approximate stems. What used to be impossible is now a button, and rights and permitted uses still depend on jurisdiction and agreements.
And how do listeners do it? Colin Cherry named the cocktail-party problem in 1953: how do people follow one voice among many? People attend to perceptual streams rather than necessarily reconstructing isolated waveforms, as Albert Bregman's auditory scene analysis of 1990 described. Their cues: a common onset, harmonicity, a common location, continuity. The methods of this part borrow each cue: panning, harmonic templates, continuity in time.
11Frontier: generative and query-based separationResearch3 min
Can a separator invent what the mixture hid?
Two frontiers. The first: a bounded nonnegative real-valued mask can only attenuate each mixture bin, and where a voice was buried there is nothing left to scale. Generative separators model what a source sounds like and fill in what was hidden, with the diffusion and token models of Part 66; check the latest. They can sound cleaner than any mask, and they can also invent: a plausible note that was never sung. For restoration that is a question of honesty: which parts of the result were recorded?
The second: fixed stems are a convention. Query-based separation lets a word, an example or a sentence name the source to extract: the saxophone, or the second guitar. And metrics that track perception are needed, since SDR disagrees with listeners, as Chapter 9 heard; learned and listening-test measures are being built. It is Part 67's question again: how do we know a separation is good?
A last frontier is the yardstick itself. The MUSDB18 benchmark of 2017 holds a hundred and fifty songs with four stems each, a hundred to train and fifty to test, and many comparable separation results have been reported on it. Fifty test songs is a small sample: a gain of a few tenths of a decibel can be chance. Its stems are studio stems, mostly Western pop and rock, so a separator tuned to it may stumble on a choir, a gamelan or a live room. And a benchmark that everyone tunes to is slowly overfitted, as Part 63's horse and the leak of Chapter 8 warn. Here Monochord has something to offer: mixtures whose stems are known, on any instrument, in any room, as many as anyone wants.
A research problem to end on. Render mixtures whose stems are known, on many instruments and in many rooms, as Monochord can. Run listening tests: which of two separations is closer to the true stem? Fit a metric to the listeners, and test it on separators it never saw. The question: can a metric rank separators as listeners do, including generative ones that invent? An answer would decide which separators are actually better.
Variation 64, recap and problemsAll tracks2 min
Every part ends by doing something to the Tune with what it built. Here the session's Tune is un-mixed: the voice alone, and the band without it, first as the network separates them, then from the stems as they were recorded.
Row sixty-four of the ledger: the separated voice decibels from the truth, the karaoke . The karaoke scores higher because what it lacks, the voice, is a small part of it, though its mistakes are just as audible.
What did we find? With one channel and many sources, separation needs assumptions. Panning and centre cancellation work in stereo; ICA can recover sources under its instantaneous independence assumptions and can fail on reverberant mixtures. Median filters split harmonic from percussive, and NMF uses each source's own templates. Ideal binary and ratio masks are useful source-informed references, not universal performance ceilings. Nonnegative real-valued masks retain the mixture phase; complex masks can change it. A network is only as good as its data, and a test that shares the training data flatters it. And SDR is not the ear: it cannot tell leakage from artifacts.
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 machines that compose, which train on stems. In generative audio, with separation by generation, and voices and their rights. In research, with listening tests. And in the concert at the end, where the Variations come apart into their stems.
And in practice. If the sources are panned apart, use that first. Report SDR and its scale-invariant cousin, with the oracle masks beside them. Listen, because leakage and artifacts sound different at the same score. And remember that a separated stem is still the recording, rights and all.
The books and papers this part follows. The full list, with notes, is in the README.
Where it goes next. Stems as training material for machines that compose in Part 65; separation by generation, voices and rights in Part 66; listening tests and leakage in Part 67; the Variations as stems in Part 68's concert.
Key results
The part's results in one place, for revision.
Try it
Lab 64 · Source separation, computed
Mix tones with drum hits, separate them three ways, score each against the truth and against the best any mask could do, unmix a stereo pair blindly, and see where the signal-to-distortion ratio disagrees with your ears.
python -m videos.music.labs 64
needs numpy, scipy, matplotlib · download lab64.py ·
source on GitHubthe mixture: tones and hits, equally loud 0.96, 0.90
median filtering (17 frames or bins): SDR tones, hits 18.2 dB, 17.7 dB
supervised NMF (6 templates each): SDR tones, hits 13.1 dB, 12.6 dB
the bounds for the tones: ideal binary, ideal ratio, ratio with true phase 20.0, 19.2, 22.4 dB
FastICA on a dry two-channel mixture: best correlation with the tones 1.0000
Griffin-Lim on the tones' true magnitude: inconsistency, SDR -18.1 dB, -2.8 dB
SDR of a perfect estimate half as loud, upside down, 1 ms late 6.0, -6.0, -4.1 dB
ear problem: the mixture, then the tones three ways; rank them by ear, then check NMF (13.1 dB) < median filter (18.2 dB) < ideal ratio mask (19.2 dB)
Every separator here is a mask on a spectrogram, bounded by the ideal masks, which need the answer; the mixture's phase is the error no mask removes; and SDR counts every difference, audible or not.
The code (107 lines; it asserts its own result)
"""Lab 64: source separation, computed: a two-source mixture of tones and drum hits pulled apart by median filtering,
by supervised NMF and by the oracle masks that bound them; a dry two-channel mixture unmixed by FastICA; Griffin-Lim's
phase, consistent but not correct; and SDR's blind spots."""
import numpy as np
from videos.coursekit import labs
from explainer.music.monochord import SR, Clip, concat
from explainer.music.monochord.mir import separate as S
from explainer.music.monochord.partkit import organ_tone
TITLE = "Source separation, computed"
GOAL = ("Mix tones with drum hits, separate them three ways, score each against the truth and against the best any mask "
"could do, unmix a stereo pair blindly, and see where the signal-to-distortion ratio disagrees with your ears.")
TASKS = [
"Change KERNEL, the median filters' length. Which length separates these tones from these hits best, and why?",
"Change RANK, the templates per source. When do more templates stop helping?",
"Change ROOM to True. Why does ICA, perfect on the dry mix, fail when each microphone hears echoes?",
]
KERNEL = 17
RANK = 6
ROOM = False
def tones(midis, seed=0, seconds=4.0):
rng = np.random.default_rng(seed)
y = np.zeros(int(seconds * SR))
for k, m in enumerate(midis):
d = float(rng.choice([0.4, 0.5, 0.8]))
z = organ_tone(440 * 2 ** ((m - 69) / 12), d, partials=6, rolloff=0.7)
i = int(k * 0.5 * SR)
if i < len(y):
y[i:i + len(z)] += z[: len(y) - i]
return y
def hits(seed=0, seconds=4.0, every=0.25):
rng = np.random.default_rng(seed)
y = np.zeros(int(seconds * SR))
n = int(0.03 * SR)
for t in np.arange(0.02, seconds - 0.05, every):
i = int(t * SR)
y[i:i + n] += rng.standard_normal(n) * np.exp(-np.arange(n) / (0.006 * SR))
return y * 0.9 / np.std(y)
def run(seed=0):
rng = np.random.default_rng(seed)
lab = labs.Lab()
melody = [60, 62, 64, 65, 67, 65, 64, 62]
a, b = tones(melody, seed), hits(seed)
x = a + b
lab.row("the mixture: tones and hits, equally loud", f"{np.std(a):.2f}, {np.std(b):.2f}")
r = S.hpss(x, harm=KERNEL, perc=KERNEL)
lab.row(f"median filtering ({KERNEL} frames or bins): SDR tones, hits", f"{S.sdr(a, r['harmonic']):.1f} dB, {S.sdr(b, r['percussive']):.1f} dB")
examples = {"tones": tones([59, 61, 63, 66, 68, 66, 63, 61], seed + 1), "hits": hits(seed + 1)}
est = S.nmf_separate(x, examples, rank=RANK, iters=100)
s_nmf = S.sdr(a, est["tones"])
lab.row(f"supervised NMF ({RANK} templates each): SDR tones, hits", f"{s_nmf:.1f} dB, {S.sdr(b, est['hits']):.1f} dB")
o = S.oracle_masks({"tones": a, "hits": b})
s_ibm, s_irm, s_tp = (S.sdr(a, o[m]["tones"]) for m in ("ibm", "irm", "true_phase"))
lab.row("the bounds for the tones: ideal binary, ideal ratio, ratio with true phase", f"{s_ibm:.1f}, {s_irm:.1f}, {s_tp:.1f} dB")
assert s_irm > S.sdr(a, x) and s_tp >= s_irm - 0.5
A = np.array([[0.9, 0.35], [0.4, 0.85]])
X = A @ np.array([a, b])
if ROOM:
h = rng.standard_normal(int(0.3 * SR)) * np.exp(-np.arange(int(0.3 * SR)) / (0.08 * SR))
h[0] = 8.0
X = np.array([np.convolve(X[0], h)[: X.shape[1]], np.convolve(X[1], h[::-1].copy())[: X.shape[1]]])
out = S.fastica(X)["S"]
corr = max(abs(np.corrcoef(a, z)[0, 1]) for z in out)
lab.row(f"FastICA on a {'room' if ROOM else 'dry'} two-channel mixture: best correlation with the tones", f"{corr:.4f}")
if not ROOM:
assert corr > 0.99
mag = np.abs(S.stft(a))
gl = S.griffin_lim(mag, len(a), iters=50)
incons = 20 * np.log10(np.linalg.norm(np.abs(S.stft(gl)) - mag) / np.linalg.norm(mag))
lab.row("Griffin-Lim on the tones' true magnitude: inconsistency, SDR", f"{incons:.1f} dB, {S.sdr(a, gl):.1f} dB")
assert S.sdr(a, gl) < s_irm
late = np.concatenate([np.zeros(48), a[:-48]])
lab.row("SDR of a perfect estimate half as loud, upside down, 1 ms late",
f"{S.sdr(a, 0.5 * a):.1f}, {S.sdr(a, -a):.1f}, {S.sdr(a, late):.1f} dB")
n = lambda y: Clip(y / np.max(np.abs(y)) * 0.8, SR)
lab.audio = concat([n(x), n(r["harmonic"]), n(est["tones"]), n(o["irm"]["tones"])], gap=0.6)
order = sorted([("median filter", S.sdr(a, r["harmonic"])), ("NMF", s_nmf), ("ideal ratio mask", s_irm)], key=lambda t: t[1])
lab.row("ear problem: the mixture, then the tones three ways; rank them by ear, then check", " < ".join(f"{k} ({v:.1f} dB)" for k, v in order))
fig, (ax1, ax2) = labs.figure(2)
X_ = np.abs(S.stft(x))[:300]
ax1.imshow(np.log10(X_ + 1e-4), origin="lower", aspect="auto", cmap="magma")
ax1.set_xlabel("frame")
ax1.set_ylabel("bin")
ax1.set_title("the mixture: lines and stripes", fontsize=8)
ax2.imshow(r["mask"][:300], origin="lower", aspect="auto", cmap="gray", vmin=0, vmax=1)
ax2.set_xlabel("frame")
ax2.set_title("the harmonic mask", fontsize=8)
lab.fig = fig
lab.note = ("Every separator here is a mask on a spectrogram, bounded by the ideal masks, which need the answer; the "
"mixture's phase is the error no mask removes; and SDR counts every difference, audible or not.")
return lab
Now change it
- Change KERNEL, the median filters' length. Which length separates these tones from these hits best, and why?
- Change RANK, the templates per source. When do more templates stop helping?
- Change ROOM to True. Why does ICA, perfect on the dry mix, fail when each microphone hears echoes?
Problems, with solutions
Try each problem before opening its solution.
-
Compute. A source is panned at θ = 70° by a sine-cosine law. What is its panning index, and how much of it survives L − R?
Solution
Here θ is measured as in Chapter 2, with 45° the centre and L = sin θ · s, R = cos θ · s. At 70°, sin θ = 0.940 and cos θ = 0.342, so the index (|L| − |R|) / (|L| + |R|) = 0.598 / 1.282 ≈ 0.47. L − R = 0.598 s; against its level in the mid channel (L + R)/2 = 0.641 s, that is 0.6 dB quieter: almost all of it survives, where a centred source would vanish.
-
Prove. Show that the ideal ratio mask minimizes the squared error of a masked estimate when the sources' phases agree in every bin.
Solution
If every source in a bin has the phase of the mixture, then S_j = a_j e^{iφ} and X = (Σ a_k) e^{iφ}, with a_k ≥ 0. The error of M X is |a_j − M Σ a_k|², minimized over real M at M = a_j / Σ a_k, the ratio mask, with zero error. When phases differ, |X| < Σ|S_k| and no real mask reaches zero: the least-squares mask is then Re(S_j X*) / |X|², the phase-sensitive mask, and the remaining error is the phase gap of Chapter 7.
-
Ear. The lab plays separations at several SDRs, some by leakage and some by artifacts; rank them, then check.
Solution
The lab prints each separation's SDR. Most listeners rank leakage of a quiet other instrument above musical noise at the same SDR; compare your ranking with the numbers and note where they disagree.
-
Build. Train the network on all four stems at once, and compare its drums with the median filter's.
Where to look. Replace the sigmoid output with four masks per bin passed through a softmax, so they share each bin; train on the same transposed phrases with the four true ratio masks as targets; score each stem's SDR against the median filter's percussive half at its best length (3.4 dB) and NMF's (8.5).
-
★ Can a metric rank separators as listeners do, including generative ones that invent?
Where the frontier is. Render mixtures whose stems are known across many instruments and rooms, separate them with masking and generative methods, collect MUSHRA-style ratings, and test which measures (SDR, SI-SDR, perceptual and learned ones) predict the ratings, and whether any notices invention.
Notes and sources
Sources
- E. Vincent, T. Virtanen and S. Gannot (eds.), Audio Source Separation and Speech Enhancement (2018); Z. Rafii et al., "An overview of lead and accompaniment separation in music", IEEE/ACM TASLP (2018); A. S. Bregman, Auditory Scene Analysis (1990).
- C. Avendano, "Frequency-domain source identification and manipulation in stereo mixes" (WASPAA, 2003); A. Hyvärinen, J. Karhunen and E. Oja, Independent Component Analysis (2001); D. FitzGerald, "Harmonic/percussive separation using median filtering" (DAFx, 2010).
- P. Smaragdis, "Non-negative matrix factor deconvolution" (ICA, 2004); T. Virtanen, "Monaural sound source separation by nonnegative matrix factorization with temporal continuity and sparseness criteria", IEEE TASLP (2007).
- D. W. Griffin and J. S. Lim, "Signal estimation from modified short-time Fourier transform", IEEE Trans. ASSP (1984); D. Stoller, S. Ewert and S. Dixon, "Wave-U-Net" (ISMIR, 2018); A. Défossez et al., "Music source separation in the waveform domain" (2019); Z. Rafii et al., "The MUSDB18 corpus for music separation" (2017).
- E. Vincent, R. Gribonval and C. Févotte, "Performance measurement in blind audio source separation", IEEE TASLP (2006); J. Le Roux et al., "SDR: half-baked or well done?" (ICASSP, 2019).
About this partfrom its README
Part 64 of a sixty-eight-part course in music (see the series plan and
the syllabus), the fourth part of Act XI, Listening Machines. A mix is a sum; a listener hears the
voice, the bass and the drums in it at once, but for a machine un-mixing one channel is like un-baking a cake. This part
builds the separators in order of what they assume: centre cancellation and panning for stereo, independent component
analysis for clean two-channel mixtures, median filtering for harmonic against percussive, supervised non-negative
matrix factorization, source-informed oracle reference masks (not universal SDR bounds), Griffin and Lim's phase, and a small network;
then how separation is measured, and where the measure and the ear part company. The tools are Monochord's
(explainer/music/monochord/mir/separate.py); the music is Part 56's session, whose every stem Monochord mixed itself,
so every separation is scored exactly.
- Un-baking a cake. An ear question (a voice and a piano on one track, then the voice twice: which was separated? the first, 12 dB from the truth); a demo cassette lifted apart decades later; the plan.
- 1. The mixing model. A mix as a sum; why separation needs assumptions; the test set (vocals, bass, drums, other, as in MUSDB18); the four stems heard alone and mixed (the voice a third of the energy).
- 2. Where things are panned. Centre cancellation (left minus right, 11 dB quieter: the centred voice, bass and drums gone), heard; a panning index per bin (the piano at 2.7 dB SDR); the session's energy by panning index (a tall centre, broad shoulders).
- 3. Independent components. Blind separation; what ICA sees; the session's voice and band as a cloud of samples, before and after; kurtosis along every direction (the voice 1.61, the microphones 1.34 and 0.82: the most non-Gaussian direction is the voice); dry and in a room, heard (correlation 0.99999, then 0.12).
- 4. Harmonic and percussive. Lines and stripes; the harmonic mask; the split heard (tonal stems 7.8 dB, drums 1.0); the filter's length (63 frames: tonal 10.1, drums 3.4); short and long filters heard.
- 5. Factorization, again. Templates for sources; the voice's combs and the drums' smears; the separated stems (drums 8.5 dB, vocals 7.7, bass 5.4, piano and guitar 5.2); how many templates (5.3 dB with one, 7.7 with six, 7.9 with twenty-four); the vocals heard.
- 6. Masks and their bounds. Oracle masks; the vocals' ideal binary and ratio masks as pictures; the reference scores (vocals: NMF 7.7, binary 8.3, ratio 9.3, ratio with true phase 12.7; for the drums the binary mask wins); the oracles heard.
- 7. The phase problem. A mask keeps the mixture's phase; Griffin-Lim's phase heard (−3.2 dB against 8.7 with the mixture's); its inconsistency falls from −4 to −20 dB while its SDR stays near −3; an ear question on the phase gap (9.3 against 12.7 dB); separating waveforms (Wave-U-Net, Demucs).
- 8. Networks that separate. Monochord's separator (five frames of log spectrum in, the vocal mask out), trained on the middle phrases transposed five ways; training; heard (6.9 dB); every method compared (below NMF's 7.7: a network is only as good as its data); what a leak is worth (trained on stretches that repeat or include the test: 8.5 dB).
- 9. Measuring separation. SDR, SI-SDR and BSS Eval; an ear question (two estimates at exactly 8.0 dB, one leaking the band, one with bins switched off); a perfect estimate changed (half as loud 6.0 dB; upside down −6.0; low-passed at 2 kHz 36.6; a millisecond late −0.6), heard; what the numbers miss.
- 10. What separation is for. Uses; an ear question on a remix (vocals up 6 dB, drums down 6, from separated stems: the first; 13.7 dB from the true remix, where the original mix is 7.0); rights; listeners.
- 11. Frontier: generative and query-based separation. Separators that invent; sources named by a query; better metrics; ★ research problem.
- Variation 64, recap and problems. The session's Tune a cappella and as karaoke, from the network and from the true stems (the voice 6.9 dB, the karaoke 10.0); the ledger; what we found; five problems; where it comes back; in practice; references; Part 65.
What is computed and built
python -m videos.music.music64.compute (about half an hour on a busy machine: the networks train) fills
.cache/music64/.
| Item | What it computes | Checked against |
|---|---|---|
hook, meet |
a voice separated from a piano by NMF; the four stems heard | the stems as rendered (tests) |
pan, panmap |
centre cancellation; per-bin panning index; the energy at each index | the stage's pan angles (tests) |
ica, icascatter |
FastICA dry and in a room; the sample cloud; kurtosis by direction | the sources mixed (tests) |
hpss, hpsssweep, hpssknob |
median-filter masks; filter length and mask power | the true stems (tests) |
nmf, nmfrank |
supervised NMF with templates from other phrases; templates per source | the true stems (tests) |
oracle, maskimg, truephase |
ideal binary and ratio masks, with the true phase; mask pictures | by definition the bounds (tests) |
phase, glcurve |
the mixture's phase and Griffin-Lim's; inconsistency against SDR | the true vocals (tests) |
net, netleak |
the vocal-mask network, honest and leaked | the true vocals (tests) |
metrics, gain, remix |
equal-SDR estimates; SDR's blind spots; a remix from separated stems | the true stems (tests) |
Monochord's tools are held in tests/music/test_separate.py; this part's claims and clips in
tests/music/test_music64.py.
Sounds. Part 56's session (vocals by Part 8's voice, double-tracked; Part 38's piano, guitar and bass; Part 40's kit), first two phrases for testing; its middle phrases for training; Part 56's stage for panning; a simulated room for ICA.
What the models are, and are not. The session is clean and dry, with stems that never bleed into each other's microphones; real multitracks bleed. The test uses the Tune's opening; its last two phrases repeat the opening note for note, so no method here learns from them (the leaked network in Chapter 8 shows why). The network is two hidden layers on five frames, trained on seconds of one band; Demucs and its successors train on hundreds of songs, with waveform branches and attention. SDR is computed directly as the energy ratio, not by BSS Eval's projections, so gains count as error.
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- Hook: an ear question (which voice was separated?); the cassette; the plan.
- The mixing model: a mix as a sum; why separation needs assumptions; the test set; the four stems, heard.
- Where things are panned: centre cancellation, heard; a panning index per bin; the session's energy by index.
- Independent components: blind separation; what ICA sees; the session as a cloud; kurtosis by direction; dry and in a room, heard.
- Harmonic and percussive: lines and stripes; the mask; the split, heard; the filter's length; short and long, heard.
- Factorization, again: templates for sources; what they learnt; the stems scored; how many templates; the vocals, heard.
- Masks and their bounds: oracle masks; the masks as pictures; the ceilings; the oracles, heard.
- The phase problem: the mixture's phase; Griffin-Lim, heard; consistent is not correct; an ear question on the phase gap; waveform separators.
- Networks that separate: Monochord's separator; training; heard; every method compared; what a leak is worth.
- Measuring separation: SDR, SI-SDR, BSS Eval; an ear question (same SDR, different faults); a perfect estimate changed, heard; what the numbers miss.
- What separation is for: uses; an ear question on a remix; rights; listeners.
- Frontier: generative and query-based separation; metrics; the research problem.
- Variation 64: the Tune a cappella and as karaoke, separated and true. Outro: problems, payoffs.
Covers: the mixing model; panning and centre cancellation; independent components; harmonic against
percussive; factorization; masks, the Wiener filter and oracle bounds; the phase problem; networks on
spectrograms and on waveforms; metrics and their faults; what it is used for.
Built and computed: monochord/mir/separate.py on Part 56's session: left minus right 11 dB down; ICA perfect
dry (0.99999) and lost in a room (0.12); median filtering (tonal 7.8 dB, 10.1 with long filters); supervised NMF
(vocals 7.7 dB) against the oracles (binary 8.3, ratio 9.3, ratio with true phase 12.7); Griffin-Lim consistent
but −3 dB; a vocal-mask network at 6.9 dB honest and 8.5 leaked; SDR's blind spots (a millisecond late −0.6 dB,
low-passed at 2 kHz 36.6); a remix from separated stems 13.7 dB from the true remix.
Variation 64: the session's Tune a cappella and as karaoke, from the network's stems and from the true ones
(the voice 6.9 dB, the karaoke 10.0).
Frontier: generative and query-based separation; metrics that track perception (verify).
Reading: Vincent, Virtanen & Gannot (eds.); Rafii et al. (2018); Le Roux et al. (2019); Défossez et al.
Build the film
python -m videos.music.music64.compute # the part's numbers, into .cache/music64
python tools/build.py music64 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py music64 Hook # one chapter, silent, with a contact sheet
Scenes: videos/music/music64. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
python -m videos.music.music64.compute # numbers and sounds (the networks train)
EXPLAINER_TTS=silent python tools/build.py music64 -q l --fps 15 # a silent-narration preview, with the sounds
python tools/qa_sound.py music64 --sync # the sound gates
python tools/dead_air.py renders/music64_480p.mp4 --sound music64 # no empty screen; no sound over a still one
python tools/lecture_length.py music64 # 30 to 60 minutes, listening included
python tools/build.py music64 # 1080p30, narrated
python -m pytest -q tests/music # Monochord against its references; this part's claims and clips
python -m videos.music.labs 64 # the lab (writes a figure and a short WAV)