Pitch, Onsets and Transcription
How does a machine hear music and write down its notes, and how do we know when it is right?
An ear question: the Tune with chords twice on one piano, a performance and a small network's transcription played back (the second was the original; the copy found 21 of 30 notes and added 43). Mozart and the Miserere in 1770; why a listening machine needs an answer key, which Monochord's renders give exactly (160 training pieces, 12 test). One voice: the difference function, the missing fundamental found at 220.0 Hz, YIN's steps (a bias of 0.02 cents against autocorrelation's 1.8), the track played as a sine beside the voice. In noise: the sung Tune tracked through three noises, heard; YIN's gross errors 9 per cent at 0 dB and 60 at -5, where plain autocorrelation keeps 10. Chords: an ear question on an added octave; salience peaking on C3, an octave below the lowest note; cancellation; the hidden octave. Onsets by spectral flux, piano against bowed strings (F 0.90 and 0.74), heard; precision against recall. NMF: multiplicative updates, blind components, note templates, a test piece factorized and played back (9 of 10 notes, 17 added, mostly at the range's edges). A network on five frames: note F 0.67 on piano against NMF's 0.49; inside it; how many notes at once (0.91 on single lines, 0.54 with six). Timbres never heard: harp, organ and strings, heard (the network 0.24 on the harp); an ear question on the organ. Keeping score: precision, recall and F; an ear question on two transcriptions at F 0.82 and 0.83, one missing notes and one with octave errors. Notes to a score: a rubato performance's exact onsets, one fixed tempo putting 1 of 14 on the written beat and a drifting tempo all 14, its tempo curve from 108 to 135; key and spelling. Fifty years of transcription; frontier: many instruments, audio to score, a research problem on calibration. Variation 61: the Tune transcribed and re-rendered five times round, F 0.53 after one round and 0.10 after five.
What you need. Part 2 for spectra and partials; Part 3 for the missing fundamental; Part 15 for keys; Part 38 for the piano; Part 48 for sampling. Autocorrelation, peak picking, non-negative least squares and the KL divergence, multiplicative updates, small neural networks and cross-entropy, precision and recall, dynamic programming.
- Ideas, mathematics and history
- YIN, salience, onset detection, non-negative matrix factorization, neural transcription, from notes to a score
- What we build, compute and hear
- a transcriber scored against known scores; the Tune after five round trips
What you will be able to do
Foundations
- Hear a pitch track as a sine beside the voice, the voice through noise, and an added octave in a chord.
- Hear transcriptions played back: NMF's busy copy, the network's on an unseen organ, two at the same F.
- Explain why polyphony and unseen timbres are hard, and why a score is not a performance.
Full course
- Track pitch by YIN and by autocorrelation and measure gross and fine errors against noise.
- Transcribe by NMF with fixed templates and by a small network; score notes and frames by precision, recall and F.
- Quantize performed onsets with a fixed and with a drifting tempo, and find the key.
Research
- Measure and improve a transcriber's calibration on timbres it never heard.
Practice
- Keep answer keys exact, report note and frame scores with their tolerances, and listen to the playback.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Foundations 27 min · Full course 33 min · Research 35 min · Practice 33 min.
- 0The holy grailFoundations2 min
- 1One voice's pitchFoundations4 min
- 2Pitch in noiseFoundations2 min
- 3Many notes at onceFoundations3 min
- 4Where notes beginFoundations2 min
- 5Factorizing the spectrogramFoundations4 min
- 6A network that listensFoundations3 min
- 7Timbres never heardFoundations2 min
- 8Keeping scoreFoundations3 min
- 9From notes to a scorePractice3 min
- 10Fifty years of transcriptionPractice2 min
- 11Frontier: many instruments, and scoresResearch2 min
- Variation 61, 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.
The holy grailFoundations2 min
In Rome in 1770, by his father's account, the fourteen-year-old Mozart wrote out Allegri's Miserere from memory. Now a machine tries. The Tune with its chords, twice, on the same piano. One is a performance; the other is a machine's transcription of that performance, played back. Which is the original?
The second was the original. The machine's copy got of its notes right, and added that were never played. Close, and not the same: this part is about that gap.
The task is old. In Rome, in 1770, the fourteen-year-old Mozart heard Allegri's Miserere in the Sistine Chapel, a nine-voice setting the Chapel kept to itself. That evening, his father wrote home, Wolfgang wrote it out from memory. To hear music and write down its notes is transcription, the oldest skill of the trained ear. For machines it has been called the holy grail of music computing.
This is the first part of Act Eleven, which turns the series' chain around: sound in, and notes, beats, names and sources out. A listening machine is only as good as its answer key, the notes that were really played. For recordings, answer keys are rare, slow to make, and argued over. Monochord makes its own sound, so commanded pitches and note-event times are known; audible onsets, offsets and expressive details still depend on the renderer, and there is no limit to how many.
Here is the plan. One voice's pitch, by YIN, and what noise does to it. Many notes at once, and the octave that hides. Where notes begin. Taking a spectrogram apart into notes, and a network that learns to listen. What happens on a timbre neither has heard, and how to keep score. And from notes to a score, and fifty years of the field.
1One voice's pitchFoundations4 min
How does a machine find the pitch of one voice?
Start with one voice. Pitch is a percept; what a machine measures is the fundamental frequency, f nought, the rate at which the wave repeats. The obvious method, taking the strongest peak of the spectrum, is often wrong: a formant can make the third harmonic the loudest. And the fundamental can be missing altogether, as Part 4 showed, while the ear still hears it. So look for repetition in time instead: how far must the wave be shifted to match itself?
Here is how YIN, published by Alain de Cheveigné and Hideki Kawahara in 2002, does it. Take a wave, here a 220-hertz tone with two overtones. Shift it by a lag tau and add up the squared differences. At a lag of one period the wave matches itself, and the difference dips to nearly nothing. YIN divides the difference by its own running average, which removes the trivial match at lag zero and puts every dip on one scale. The first suitable local minimum below a threshold, a tenth here, estimates the period: one two-hundred-and-twentieth of a second. The same dip recurs at two and three periods; taking the first avoids reporting the octave below.
Listen to a tone made of the second to eighth partials of 220 hertz, with nothing at 220 itself. You still hear 220, and so does YIN, because the wave still repeats every two-hundred-and-twentieth of a second.
YIN improves on plain autocorrelation in four steps. It uses the difference function, which does not favour short lags the way autocorrelation of a finite frame does. It divides by the running mean, so the match at lag zero disappears and every dip is on one scale. It takes the first dip under a threshold, which helps reduce octave errors under suitable signal conditions. And it interpolates between lags, for accuracy finer than one sample. On a steady tone, YIN is within cents; the plain autocorrelation of the same frame is pulled cents sharp.
A pitch tracker can be checked by ear. Hear the sung Tune; then YIN's pitch track, played as a pure tone that follows it; then the two together.
Where the tracker is right, the tone and the voice fuse into one sound; an octave error or a wrong note can become easier to notice as a second line. Researchers listen to their pitch tracks this way, because a wrong frame is easier to hear than to find in a table.
Tracking one voice's pitch is everywhere. In tuners: a pitch tracker and a needle, in every guitarist's pocket. In pitch correction: Auto-Tune, released in 1997, grew out of autocorrelation methods its inventor, Andy Hildebrand, had used to read seismic data for oil exploration. In query by humming, in singing lessons that score intonation, in karaoke. In speech, for intonation and stress, and in biology, for bird song and whale song. And in every analysis of a sung performance in this series.
2Pitch in noiseFoundations2 min
How much noise can a pitch tracker take?
Here is Part 8's voice singing the Tune's opening, with white noise twenty decibels down, as loud as the voice, and ten decibels louder. Watch YIN's estimates against the notes sung.
Now count. The share of frames that YIN gets wrong by more than twenty percent, a gross pitch error under this twenty-percent threshold, which also includes smaller-than-octave errors, against the noise. Clean, almost none; with the noise as loud as the voice, percent; ten decibels louder, . The plain autocorrelation of the same frames does in heavy noise: percent at minus ten. It averages over the whole frame, and white noise has no period to confuse it, while YIN's threshold, designed for clean speech, finds no dip and has to guess.
The lessons. No single method wins everywhere: YIN is accurate and cheap on clean sound, and averaging helps in noise. Real noise is worse than white: other voices, other instruments and reverberation, all with periods of their own. Later methods track pitch over time: probabilistic YIN, in 2014, keeps several candidates in each frame and chooses a smooth path through them. CREPE, in 2018, is a network trained on several pitch-annotated datasets, including recorded and synthesized material; our teaching network is trained on one synthetic instrument. And the method that matters: measure on the noise you will meet, with an answer key.
3Many notes at onceFoundations3 min
Why is a chord so much harder than a melody?
A melody has one note at a time; music mostly does not. One note has one period and one comb of partials. A chord adds several combs, and the wave no longer repeats at any of their periods, so a single-period tracker can return a shared period or subharmonic rather than identify each note. Worse, the combs share teeth. In exact three-to-two tuning, C and G share every third C partial; equal temperament and inharmonic instruments give near-overlaps instead; an octave shares every partial of its upper note. So the question becomes: which set of combs explains this spectrum?
Your turn. Two piano chords. Are they the same chord, or does one have a note the other lacks?
Different. The second adds a C an octave above the lowest note. It makes the chord a little brighter, and it is easy to miss, for the reason we just saw: ideal harmonic spectra overlap this way; real piano inharmonicity, attacks and independent decay can supply extra cues.
One answer is salience, after Anssi Klapuri. For every candidate note, add up the spectrum at its first eight partials, each weighted a little less than the one before. For C-E-G the notes played stand out, but not alone: each note's octave below collects the same partials, plus a few, and so do notes whose partials happen to land on the chord's. Salience ranks candidates; it does not decide which are there.
Salience ranks; a second step decides. Klapuri's method estimates and cancels. Find the most salient candidate. Subtract its partials from the spectrum, but not all of a shared partial: real spectra are smooth, so take only the share that a smooth envelope through the note's other partials predicts. Repeat until what is left has no salient pitch. Anssi Klapuri published this in 2003 and refined it in 2006; later methods estimate whole sets of notes jointly. And the octave? Only an unusually bright, uneven run of even partials betrays an upper octave sitting on a lower note.
Here is what the two transcribers of the coming chapters report for the two chords. The plain triad: . With the octave added, Octaves are the classic failure of transcription, by machines and by people.
4Where notes beginFoundations2 min
How does a machine hear a note start?
Notes have to begin somewhere. A note's start is energy appearing, suddenly, in frequency bands where there was little. Spectral flux measures exactly that: from each frame to the next, add up the increases of the log-compressed spectrum. The logarithm lets a quiet note's start count as well as a loud one's. Only increases count: a note ending is not a note beginning. Then pick peaks: a local maximum, above the local mean, and not too soon after the last one.
Hear the Tune's opening, repeated notes and all, on the piano and then on bowed strings, with the flux and the detected onsets drawn under each.
The piano's hammers make sharp peaks, and the detector finds of onsets. A bow starts a note gradually, and a repeated note on the strings barely changes the spectrum at all: of .
Every detector has a threshold, and it trades one error for another. Lower it, and the detector finds more of the real onsets, but reports more false ones; raise it, and it reports fewer, missing more. Here is the trade, threshold by threshold, for the piano. And for the bowed strings, whose curve never reaches the piano's corner: no threshold separates their gentle starts from the swells within notes. The best F-measures are and .
What makes onsets hard? Soft onsets: bowed, blown and sung notes swell rather than strike. Repeated notes: the same pitch again changes little but the loudness. Vibrato and glides: pitch changes that are not new notes. So onset detectors add pitch and phase information, and networks learn onsets from examples, as Onsets and Frames does in Chapter 10.
5Factorizing the spectrogramFoundations4 min
Can a spectrogram be taken apart into notes?
In 2003 Paris Smaragdis and Judith Brown proposed treating the problem as algebra. Write the spectrogram V as the product of two matrices, W times H, all three non-negative. V is frequency by time. Each column of W is a note's spectrum, its comb of partials. Each row of H is that note's activation: how loud it is in each frame. Non-negative because sounds only add, roughly, in a magnitude spectrogram: magnitude additivity is only an approximation; underlying complex spectra can interfere, so the parts must be additive, like notes.
How are W and H found? By Daniel Lee and Sebastian Seung's multiplicative updates: multiply each entry of H by a ratio that compares the spectrogram with its current reconstruction, and then do the same for W. Entries that start non-negative stay non-negative, and ideal multiplicative updates have a non-increasing objective under their assumptions; finite precision and numerical safeguards need to be checked. Here it is falling, iteration by iteration, on a test piece.
Left to itself, what does the factorization find? Here are twelve components learnt from one test piece alone, each labelled with the piano note it most resembles. of them look like a single piano note. The rest are mixtures: notes that often sounded together, or the noise of attacks. The piece uses pitches. Twelve components could accommodate those pitches, but nothing told the factorization that a component should be a note.
Left to itself, NMF finds parts, but not necessarily notes. So Monochord learns W in advance. Each column is one piano note's spectrum, learnt from that note played alone; the diagonal lines are the partials, rising with the note. Then W is fixed, and only the activations are learnt from the music: supervised transcription.
Here is a test piece of random polyphony on the piano, never used to learn the templates, and its activations, with the notes really played boxed in white.
The boxes fill with light where the factorization agrees. Scored note by note, it finds percent of the notes, and percent of what it reports is right.
Transcriptions are easiest to judge by playing them back. Hear the test piece, then NMF's transcription of it on the same piano.
It found of the notes, and added that were never played. The playback sounds busier. Most of the extras sit at the very edges of the range, on the lowest and highest templates, which soak up whatever energy no other template explains, a thump or a hiss; the rest strike again a note that is still sounding, as its decay drifts away from the template's shape.
NMF has limits. Its templates assume every note of a pitch has one spectrum, but loud notes are brighter, and notes change as they decay. Activations leak: a note's partials are partly explained by its neighbours. On our piano test pieces its F-measure is , and on other timbres it is worse, as Chapter 7 shows. There are refinements: sparsity, continuity in time, templates that change over a note, harmonic constraints. NMF's virtue is that every part of it can be read; its vice is that it knows nothing it was not told.
6A network that listensFoundations3 min
What can a machine learn from examples that it cannot be told?
The other route is to learn from examples. Monochord's network is small: it reads five neighbouring frames of the log-frequency spectrogram, passes them through two layers of two hundred and fifty-six units, and outputs, for each of the thirty-seven notes from C3 to C6, a sigmoid activation interpreted as a sounding-note score; weighted training does not guarantee calibrated probabilities. It is trained by binary cross-entropy against the answer key, with the rare positive frames weighted up. Nobody tells it what a partial is.
The training set is a convenient source of exact commanded labels; the field also uses synthetic data and instrument-linked recordings: pieces of random polyphony, six seconds each, notes, every one with an exact answer, because Monochord played it. All on one instrument, Part 38's piano. The loss falls over the epochs, and the network has learnt what a piano note looks like from the inside.
On twelve new piano pieces, never heard in training: the factorization's note F-measure is ; the network's, . But both were trained on this piano. The real test is a timbre neither has heard.
What has it learnt? Here are six of the first layer's two hundred and fifty-six units, the ones with the largest weights: each is a pattern over five frames and the log-frequency bins. Many are combs, bright at a set of partials and dark between them: learnt templates, like NMF's, but with negative weights too, so a unit can say not this note as well as this one. Some respond to a change from frame to frame: an onset. The feature basis and architecture are designed; these displayed patterns are learned weights, not proof of a unit's causal function.
Here is the same piano test piece the factorization heard in Chapter 5, now as the network hears it: its probability for every note in every frame.
Compared with the factorization's activations, the picture is cleaner: the network has learnt to stay quiet on the octaves and twelfths that share a note's partials. Note by note it scores on this piece.
How does each transcriber cope as the music thickens? On new piano pieces allowing one note at a time, then two, three, four and six: the network scores on single lines and falls to with six voices; NMF falls from to . Every added voice puts more partials on top of each other, and more of each note's evidence is shared with another's. The gap between the two is what learning from examples buys, on the instrument it learnt.
7Timbres never heardFoundations2 min
Does a transcriber trained on a piano hear an organ?
Here is one test piece on four instruments: the piano both transcribers learnt from, then a plucked harp, an organ and bowed strings, none of which either has ever heard.
And the scores. On the piano, both do well. On the instruments they never heard, both fall: the factorization worst on the , the network worst on the . A template of a piano note does not fit an organ's partials, and a network that has only seen hammers does not know what a bow does to the start of a note. This is the field's central difficulty, measured exactly: transcribers are only as general as what they were shown.
Your turn. A piece on the organ, and the network's transcription of it, played back on the same organ. Which was the original?
The first was the original. The copy found of its notes and added that were not there; you may have heard notes drop out, or stray notes an octave or a twelfth away, where the organ's partials fooled the network.
What to do about it? Train on many timbres: the obvious remedy, and Monochord can render as many as it likes. Augment: change the brightness, the room, the noise and the tuning at random during training. But rendered sound is not recorded sound; robotics calls it the gap from simulation to reality, and music has it too. The honest test is always a timbre, a room and a player the system never met.
8Keeping scoreFoundations3 min
When is a transcribed note right?
How should a transcription be scored? Frame by frame: for each twenty milliseconds and each pitch, sounding or not. Note by note: a reported note is right if its pitch matches a played note and its onset is within fifty milliseconds. Stricter still, its end must match too. Precision is the share of reported notes that are right; recall, the share of played notes found; F, their harmonic mean. Each played note can be matched only once, using maximum-cardinality one-to-one matching, as mir_eval does; our implementation matches exact integer MIDI pitch and uses the stated time tolerances.
Here is the organ piece you just heard, scored. White boxes: the notes played. Gold: the network's notes that match one. Red: its notes that match nothing, often an octave away from a real note, or a real note broken in two.
Your turn. Two transcriptions of the Tune with its chords, played back. They score almost the same. One is missing notes; the other has some notes in the wrong octave. Which is which?
The first is missing of the notes; the second has notes an octave out. Their F-measures are and . To a listener, a missing note leaves a gap that the harmony often covers, while a note in the wrong octave can break the melody's line. Which is worse depends on what the transcription is for, and one number cannot say.
The same network, counted two ways, on all four instruments. Frame by frame. And note by note. The two disagree because they punish different things: a note held too short costs frames but not the note, while a note broken in two costs a note but few frames. Always report which you counted.
The numbers are useful, and limited. A metric is a choice: fifty milliseconds is generous for a drum and strict for a slow violin entry. An F-measure hides which errors were made: an octave error and a missed note cost the same. Real answer keys are made by people, and people disagree; instrument-linked or synthetic MIDI provides precise event commands, but acoustic alignment, pedal and audible offsets still need interpretation. And a transcription that scores nine tenths can still be unreadable, while one that scores seven tenths can be useful. Readability is Chapter 9's subject.
9From notes to a scorePractice3 min
How do performed seconds become written beats?
A list of notes is not yet a score. A transcriber reports notes in seconds; a score is written in beats. And players stretch and squeeze time: rubato, held phrase ends, a slower start. So the next step is to find the tempo, snap each onset to the nearest fraction of a beat, and read off the durations. Then come the rest of a score's decisions: meter and barlines, key and spelling, voices and staves.
Here is the Tune's opening played with rubato: a slower middle, a held phrase end. To study quantization alone, give the quantizer its onsets exactly, as a perfect transcriber would. In seconds, they drift. The simplest quantizer tries every fixed tempo and phase and snaps each onset to the nearest half beat. It settles on beats a minute, and only of the onsets land where the Tune is written: one tempo cannot fit a performance whose tempo moves. So let the tempo drift, a little from note to note, and prefer simple note values; find the likeliest values and tempos together by dynamic programming. Now of land on their beats.
And the tempos it chose are the rubato itself: slowing to beats a minute through the first phrase and pressing on to in the second, around the 120 at which the Tune is written. A score and a tempo curve together describe the performance; the score alone is the plan. Cemgil and Kappen built quantizers like this in 2003; Part 62's beat tracker does the same job from audio.
Hear the performance, then the score the drifting-tempo quantizer wrote, played strictly at 120.
The score keeps the notes and the beats, and loses the rubato, as it should: a score is a plan for a performance, not a performance.
Next, the key. Part 15's key finder, run on the transcribed notes weighted by their quantized durations, ranks first, ahead of and . Key alone does not fix chromatic spelling: in C major, F sharp may lead toward G, while G flat can have a different harmonic or voice-leading role. And it decides the key signature, and which notes need accidentals.
Everything else a score needs is a further decision. Meter: where the barlines go, from accents and harmony, which Part 62's beat trackers take up. Key and spelling: is a note G sharp or A flat? Part 15's key finder supplies one clue; local harmony and voice leading also affect spelling. Voices and staves: which notes belong to which hand, and which line. Tuplets, grace notes, ties across barlines: each a decision a musician makes without noticing. A readable score is the last and least solved step.
10Fifty years of transcriptionPractice2 min
How did machines learn to write down what they hear?
The field is fifty years old. Between 1975 and 1977 James Moorer at Stanford had a program transcribe duets, provided neither voice's pitch was a harmonic of the other's. Through the 1990s and 2000s, systems of rules gave way to statistics: Anssi Klapuri's multiple-pitch estimator of 2003 used harmonicity and the smoothness of real spectra. In 2003 Paris Smaragdis and Judith Brown factorized a piano's spectrogram into notes, the method of Chapter 5. For a single voice, YIN in 2002, then SWIPE, a probabilistic YIN in 2014, and in 2018 CREPE, a network. And in 2016 Siddharth Sigtia, Emmanouil Benetos and Simon Dixon trained a network to transcribe polyphonic piano end to end.
What changed most was data with answers. In 2010 MAPS recorded a Disklavier, a piano that records the keys it plays, giving instrument-linked note labels, with alignment, pedal and acoustic-boundary limitations. In 2018 Curtis Hawthorne and colleagues' Onsets and Frames used one network to find where notes begin and another for how long they last, each helping the other. In 2019 they released MAESTRO: about two hundred hours of competition pianists on Disklaviers, notes aligned to a few milliseconds. With that much data, reported onset-based piano note F-measures exceeded nine tenths in particular benchmarks; offset-aware and cross-domain scores differ on recordings like the training set. The lesson is the one Monochord teaches too: transcription is limited by its answer keys.
And how do people do it? In 1770, his father wrote, the fourteen-year-old Mozart wrote out Allegri's Miserere after hearing it in the Sistine Chapel. He knew the style, the harmony and the voices' ranges: a strong prior over what was likely. Trained musicians transcribe by expectation as much as by hearing: they hear what fits, and check. A model of music, like Chapter 9's grid or Part 14's melodies, is how a machine gets such a prior.
11Frontier: many instruments, and scoresResearch2 min
Can a machine transcribe a band?
Two frontiers. The first is the whole band. In 2022 MT3, from Josh Gardner and colleagues, had a transformer read a spectrogram and write note events for every instrument, like a translation. The same year Basic Pitch offered a compact instrument-agnostic transcriber, with limits on mixtures, range and playing conditions, light enough for a phone. On real recordings of many instruments, results still fall well short of solo piano; check the latest numbers, which move each year. The bottleneck is again the answer key: real bands are rarely recorded with their exact notes. Synthetic data like Monochord's helps, and the gap between rendered and real sound is the open question.
The second is the score itself. A note list is not a score: a score has a meter, bars, voices, a key and spelled notes. Models now write scores directly, in score languages, from audio or from note lists. And a score's errors are not a note list's: one wrong tempo misplaces every barline. So evaluation is unsettled: how far is one score from another, as a musician would judge it?
A research problem to end on, from Chapter 7. Render pieces on many instruments, with exact answer keys, and hold some timbres out. Have a transcriber report, for every note, the probability that it is right. Check those probabilities on the held-out timbres: are notes it calls ninety percent sure right ninety percent of the time? The question: can a transcriber stay calibrated on a timbre it has never heard? An answer would tell a musician which notes of a machine's transcription to check.
Variation 61, recap and problemsAll tracks2 min
Every part ends by doing something to the Tune with what it built. Here the Tune with its chords goes round the loop: played on the piano, transcribed by the network, and played again from the transcription, five times. You hear the original, and the Tune after one, three and five rounds.
Row sixty-one of the ledger, the first of Act Eleven. After one round the copy's note F-measure against the original is ; after five, .
What did we find? YIN finds one voice's period from a normalized difference function, and heavy noise defeats it. Chords overlay combs of partials; salience ranks the candidates, and octaves hide. Spectral flux finds onsets, but bowed and repeated notes are hard. NMF factors a spectrogram into templates and activations. A small network trained on rendered piano does better, on piano. Both lose accuracy on these tested unseen timbres; the degree varies; and quantization turns performed notes into beats.
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 beat and chord recognition, the rest of the score. In finding music, from spectrogram peaks. In source separation, with NMF again and masks. In machines that compose, with notes as tokens. And in the round trip from score to sound to score that ends the series.
And in practice. For pitch, YIN or its probabilistic cousin on clean single voices, and a network in noise. For polyphony, a network trained on the instrument you have. Check any transcription by listening to it played back. And score it note by note, with and without offsets, by the shared library.
The books and papers this part follows. The full list, with notes, is in the README.
Where it goes next. Beats, chords and form from the same spectral flux and templates in Part 62; pitch contours for query by humming in Part 63; NMF again, for sources, in Part 64; transcriptions as training data for machines that compose in Part 65; the evaluation questions of Part 67.
Key results
The part's results in one place, for revision.
Try it
Lab 61 · Pitch, onsets and transcription, computed
Track one voice's pitch with YIN as noise rises, find where notes begin, and transcribe polyphony by factorizing a spectrogram with note templates learnt from one instrument, then score it, note by note, on that instrument and on one it never heard.
python -m videos.music.labs 61
needs numpy, scipy, matplotlib · download lab61.py ·
source on GitHubG3 tone at +20 dB: YIN and autocorrelation gross errors 0%, 0%
G3 tone at +10 dB: YIN and autocorrelation gross errors 0%, 0%
G3 tone at +0 dB: YIN and autocorrelation gross errors 0%, 0%
G3 tone at -5 dB: YIN and autocorrelation gross errors 12%, 3%
harp onsets (threshold 0.07): precision, recall 0.46, 0.86
NMF with organ templates on the organ: note F 0.62
NMF with organ templates on the harp: note F 0.32
ear problem: four organ chords; which have the C an octave up? (listen first) no, no, yes, yes
YIN finds one voice's period by a normalized difference function; spectral flux finds where notes begin; NMF explains a spectrogram with one template per note; and every one of them is only as good as the sound it was built for.
The code (119 lines; it asserts its own result)
"""Lab 61: pitch, onsets and transcription, computed: YIN against noise, spectral-flux onsets, and NMF with note
templates, scored against exact answer keys on a timbre it learnt and one it never heard."""
import numpy as np
from videos.coursekit import labs
from explainer.music.monochord import SR, Clip, concat
from explainer.music.monochord.instruments.strings import karplus_strong
from explainer.music.monochord.mir import transcribe as TR
from explainer.music.monochord.partkit import organ_tone
TITLE = "Pitch, onsets and transcription, computed"
GOAL = ("Track one voice's pitch with YIN as noise rises, find where notes begin, and transcribe polyphony by factorizing "
"a spectrogram with note templates learnt from one instrument, then score it, note by note, on that instrument "
"and on one it never heard.")
TASKS = [
"Change SNRS. At what noise level does YIN start making octave errors on the test tone?",
"Change DELTA, the onset threshold. Plot precision against recall on the harp.",
"Learn the templates from the harp instead of the organ (TRAIN). Which instrument is now hard?",
]
SNRS = [20, 10, 0, -5]
DELTA = 0.07
TRAIN = "organ"
LO, HI = 55, 79
def note(inst, m, dur):
hz = float(TR.midi_hz(m))
if inst == "organ":
y = organ_tone(hz, dur, partials=6, rolloff=0.7)
k = int(0.02 * SR)
y[:k] *= np.linspace(0, 1, k)
y[-k:] *= np.linspace(1, 0, k)
else:
y = karplus_strong(hz, dur + 0.2, seed=m)
return y / (np.sqrt(np.mean(y[: int(0.2 * SR)] ** 2)) + 1e-12) * 0.1
def render(notes, inst, seconds):
y = np.zeros(int(seconds * SR) + SR)
for m, a, b in notes:
z = note(inst, m, b - a)
k = int(a * SR)
y[k:k + len(z)] += z
return y[: int(seconds * SR)] / (np.max(np.abs(y)) + 1e-12) * 0.9
def piece(seed, seconds=5.0):
rng = np.random.default_rng(seed)
out, t = [], 0.0
while t < seconds - 1.0:
for _ in range(rng.poisson(0.4)):
m = int(rng.integers(LO, HI + 1))
if all(not (n[0] == m and n[1] <= t < n[2]) for n in out):
out.append((m, round(t, 3), round(t + float(rng.choice([0.25, 0.5])), 3)))
t += 0.125
return out
def run(seed=0):
rng = np.random.default_rng(seed)
lab = labs.Lab()
t = np.arange(SR) / SR
x = sum(a * np.sin(2 * np.pi * 196.0 * (k + 1) * t) for k, a in enumerate((0.3, 1.0, 0.7, 0.5)))
for snr in SNRS:
y = x + rng.standard_normal(len(x)) * np.std(x) * 10 ** (-snr / 20)
a, b = TR.yin(y, SR), TR.acf_f0(y, SR)
truth = np.full(len(a["f0"]), 196.0)
ga = TR.gross_error(a["f0"], truth)
lab.row(f"G3 tone at {snr:+d} dB: YIN and autocorrelation gross errors", f"{100 * ga:.0f}%, {100 * TR.gross_error(b['f0'], truth[:len(b['f0'])]):.0f}%")
if snr == max(SNRS):
assert ga < 0.05 # clean enough, YIN finds the period
mel = [(60 + p, 0.4 * i, 0.4 * i + 0.35) for i, p in enumerate([0, 0, 7, 7, 9, 9, 7])]
yh = render(mel, "harp", 3.4)
o = TR.onset_strength(yh, SR)
est = TR.pick_onsets(o["odf"], o["hop_s"], delta=DELTA)
s = TR.onset_scores([n[1] for n in mel], est.tolist())
lab.row(f"harp onsets (threshold {DELTA}): precision, recall", f"{s['precision']:.2f}, {s['recall']:.2f}")
assert s["recall"] > 0.5 # a plucked string's attacks are easy to find
spectra = {}
for m in range(LO, HI + 1):
S = TR.logfreq(note(TRAIN, m, 0.8), SR)["S"]
spectra[m] = S[:, 1:30]
W, keys = TR.note_templates(spectra)
fs = {}
for inst in ("organ", "harp"):
f = []
for k in range(4):
nt = piece(100 + k)
S = TR.logfreq(render(nt, inst, 5.0), SR)
H = TR.nmf(S["S"], W=W, fix_W=True, iters=100)["H"]
est = TR.activations_to_notes(H, keys, S["hop_s"], on=0.12, rel=True)
f.append(TR.note_scores(nt, est)["f"])
lab.row(f"NMF with {TRAIN} templates on the {inst}: note F", f"{np.mean(f):.2f}")
fs[inst] = float(np.mean(f))
if TRAIN == "organ":
assert fs["organ"] > fs["harp"] # templates fit the instrument they came from
# the ear problem: chords with and without an added octave
chords = []
order = list(rng.permutation(4))
for i in order:
base = [(60, 0, 1.2), (64, 0, 1.2), (67, 0, 1.2)] + ([(72, 0, 1.2)] if i % 2 else [])
chords.append((Clip(render(base, "organ", 1.4), SR), bool(i % 2)))
lab.audio = concat([c for c, _ in chords], gap=0.5)
lab.row("ear problem: four organ chords; which have the C an octave up? (listen first)", ", ".join("yes" if h else "no" for _, h in chords))
fig, (ax1, ax2) = labs.figure(2)
ax1.plot(o["t"], o["odf"], color=labs.GOLD, lw=1)
for n in mel:
ax1.axvline(n[1], color="0.6", lw=0.6)
ax1.set_xlabel("s")
ax1.set_ylabel("flux")
ax2.imshow(np.log10(W + 1e-4), aspect="auto", origin="lower", cmap="magma")
ax2.set_xlabel("template (pitch)")
ax2.set_ylabel("log-frequency bin")
lab.fig = fig
lab.note = ("YIN finds one voice's period by a normalized difference function; spectral flux finds where notes begin; "
"NMF explains a spectrogram with one template per note; and every one of them is only as good as the sound "
"it was built for.")
return lab
Now change it
- Change SNRS. At what noise level does YIN start making octave errors on the test tone?
- Change DELTA, the onset threshold. Plot precision against recall on the harp.
- Learn the templates from the harp instead of the organ (TRAIN). Which instrument is now hard?
Problems, with solutions
Try each problem before opening its solution.
-
Compute. A transcriber reports 40 notes, of which 30 match the 36 played. What are its precision, recall and F-measure?
Solution
Precision 30/40 = 0.75; recall 30/36 = 0.833; F = 2PR/(P + R) = 2 × 0.75 × 0.833 / 1.583 ≈ 0.79.
-
Prove. Show that the multiplicative update for H leaves the KL divergence unchanged when V = WH exactly.
Solution
The update is H ← H ⊙ (Wᵀ(V ⊘ WH)) ⊘ (Wᵀ1). If V = WH, then V ⊘ WH = 1 (all ones), so the numerator is Wᵀ1 and the factor is exactly 1 in every entry: H does not change, and neither does the divergence, which is zero, its minimum. (More generally, the update never increases the divergence, by Lee and Seung's auxiliary-function argument.)
-
Ear. The lab plays chords with and without an added octave; which have it? Then check the transcriber.
Solution
The lab prints which chords had the octave and what the transcriber reported. An added octave mostly brightens the chord rather than adding a note one hears separately; Chapter 3's network missed the added C5 for the same reason, its partials lying on the lower C's.
-
Build. Train the network on piano and harp together; measure it on the organ and the strings.
Where to look. Render the training pieces on both instruments (half each, or every piece twice), keep the test pieces and their gains, and compare the note F on the organ and strings with the piano-only network's 0.52 and 0.53. Mixed training usually trades a little on each seen timbre for more on unseen ones.
-
★ Can a transcriber stay calibrated on a timbre it has never heard?
Where the frontier is. A calibrated transcriber's note probabilities match how often it is right. Measure calibration (reliability diagrams, expected calibration error) on seen and unseen timbres, then try temperature scaling on a few labelled seconds, conformal note sets, or self-training on the new timbre.
Notes and sources
Sources
- M. Müller, Fundamentals of Music Processing (2nd ed., 2021); A. Klapuri and M. Davy (eds.), Signal Processing Methods for Music Transcription (2006); E. Benetos, S. Dixon, Z. Duan and S. Ewert, "Automatic music transcription: an overview", IEEE Signal Processing Magazine (2019).
- A. de Cheveigné and H. Kawahara, "YIN, a fundamental frequency estimator for speech and music", JASA (2002); A. P. Klapuri, "Multiple fundamental frequency estimation based on harmonicity and spectral smoothness", IEEE TSAP (2003).
- J. P. Bello et al., "A tutorial on onset detection in music signals", IEEE TSAP (2005); S. Dixon, "Onset detection revisited" (DAFx, 2006).
- D. D. Lee and H. S. Seung, "Algorithms for non-negative matrix factorization" (NIPS, 2001); P. Smaragdis and J. C. Brown, "Non-negative matrix factorization for polyphonic music transcription" (WASPAA, 2003).
- C. Hawthorne et al., "Onsets and Frames: dual-objective piano transcription" (ISMIR, 2018) and "Enabling factorized piano music modeling and generation with the MAESTRO dataset" (ICLR, 2019); J. Gardner et al., "MT3: multi-task multitrack music transcription" (ICLR, 2022); C. Raffel et al., "mir_eval" (ISMIR, 2014).
- A. T. Cemgil and B. Kappen, "Monte Carlo methods for tempo tracking and rhythm quantization", JAIR (2003); J. A. Moorer, "On the transcription of musical sound by computer", Computer Music Journal (1977).
Note scoring uses maximum-cardinality one-to-one matching with exact integer MIDI pitches and stated timing tolerances; it does not call mir_eval. Network activations are not demonstrated to be calibrated probabilities.
About this partfrom its README
Part 61 of a sixty-eight-part course in music (see the series plan and
the syllabus), the first part of Act XI, Listening Machines. In 1770 the fourteen-year-old Mozart
heard Allegri's Miserere in the Sistine Chapel and wrote it out from memory; for machines, hearing music and writing down
its notes has been called the holy grail of music computing. Act XI turns the series' chain around, sound in and notes
out, and this part builds the first listeners: YIN for one voice's pitch and what noise does to it, salience and the
octave that hides in a chord, spectral flux for onsets, non-negative matrix factorization with note templates, a small
network that learns from examples, what both do on timbres they never heard, how to keep score, and how performed seconds
become written beats. The tools are Monochord's (explainer/music/monochord/mir/transcribe.py and neural.py); every
piece is rendered by Monochord, so commanded note labels are known; acoustic boundaries and pedal still require interpretation.
- The holy grail. An ear question (the Tune with chords twice: which is the performance and which a network's transcription played back? the second was the original; the copy found 21 of 30 notes and added 43); Mozart and the Miserere; why a listening machine needs an answer key (160 training pieces, 2,252 notes; 12 test pieces); the plan.
- 1. One voice's pitch. The problem; the difference function; the missing fundamental (partials 2 to 8 of 220 Hz, found at 220.0); YIN's steps (normalization, a threshold, interpolation: a bias of 0.02 cents against 1.8 for plain autocorrelation); YIN's track played as a sine beside the voice, heard; uses.
- 2. Pitch in noise. The sung Tune with noise 20, 0 and −10 dB down, tracked and heard; gross errors against noise (YIN 9 % at 0 dB, 60 % at −5, where autocorrelation is still at 10 %: in heavy white noise the plainer method is the more robust); lessons.
- 3. Many notes at once. Why a chord is harder; an ear question (C–E–G against C–E–G–C: not the same); salience, its peak on C3, an octave below the lowest note played; iterative cancellation (Klapuri); the hidden octave.
- 4. Where notes begin. Spectral flux; the Tune on piano and on bowed strings, heard with the onsets drawn (F 0.90 and 0.74); precision against recall as the threshold moves; what makes onsets hard.
- 5. Factorizing the spectrogram. NMF; the multiplicative updates; components found blind; note templates from isolated piano notes; a test piece factorized and heard; its transcription played back (9 of 10 notes found, 17 added, mostly on the range's edges); limits.
- 6. A network that listens. Design (five frames of log spectrum in, 37 note probabilities out); training on 48,160 frames; results (piano note F 0.67 against NMF's 0.49); inside the network; a test piece heard; how many notes at once (from 0.91 on single lines to 0.54 with six voices; NMF from 0.63 to 0.45).
- 7. Timbres never heard. One piece on piano, harp, organ and strings, heard; the scores (the network falls to 0.24 on the harp, NMF to 0.35); an ear question on the organ (the first was the original); why.
- 8. Keeping score. Note-level precision, recall and F; an example; an ear question (two transcriptions at F 0.82 and 0.83: the first is missing 9 of 30 notes, the second has 5 an octave out); frame-level scores; what the keys contain.
- 9. From notes to a score. Seconds are not beats; the Tune's opening with rubato, its exact onsets quantized: one fixed tempo (180 a minute) puts 1 of 14 on the written beat, a tempo that may drift puts all 14; the tempo curve it chose (108 to 135 around the written 120); the performance and the score, heard; key (C major, r = 0.97) and spelling; the rest of a score.
- 10. Fifty years of transcription. Early systems (Moorer, 1977); data and benchmarks; what the ear still does better.
- 11. Frontier: many instruments, and scores. Multi-instrument transcription; audio to score; ★ research problem: can a transcriber stay calibrated on a timbre it has never heard?
- Variation 61, recap and problems. The Tune performed, transcribed and re-rendered, five times round (note F against the original 0.53 after one round, 0.10 after five); the ledger; what we found; five problems; where it comes back; in practice; references; Part 62.
What is computed and built
python -m videos.music.music61.compute (an hour or more on a busy machine: the network trains, once, into
.cache/music61/net.pt) fills .cache/music61/.
| Item | What it computes | Checked against |
|---|---|---|
data |
160 training and 12 test pieces of random polyphony, C3 to C6 | by construction |
pitch, pitchheard |
YIN and autocorrelation on the sung Tune in noise; the missing fundamental; the track as a sine | the notes sung (tests) |
chords |
salience, NMF and the network on C–E–G and C–E–G–C | the notes played (tests) |
onsets |
spectral flux and peak picking on piano and strings; a threshold sweep | the onsets played (tests) |
nmf, nmfheard |
templates; NMF transcription of every test piece on four instruments | the notes played (tests) |
net, polyphony, timbres, hook |
the network's transcriptions; F against polyphony; unseen timbres | the notes played (tests) |
scoreheard |
two transcriptions at the same F, by dropping and by octave errors | by construction (tests) |
score |
fixed-tempo and drifting-tempo quantization of a rubato performance; key | the written beats (tests) |
tune61 |
Variation 61's five rounds | the original notes (tests) |
Monochord's tools are held in tests/music/test_transcribe.py; this part's claims and clips in
tests/music/test_music61.py.
Sounds. Part 38's piano (with the damper that ends each note's string force over 80 ms); a Karplus–Strong harp; an organ; Part 9's bowed strings; Part 8's voice; white noise.
What the models are, and are not. YIN here has no voicing model beyond its aperiodicity; the onset detector is spectral flux with a moving threshold. NMF has one fixed template per pitch, learnt from isolated notes of one piano. The network sees five frames of a log-frequency spectrogram and outputs 37 independent note probabilities; it has no onset head, no language model of notes and no data beyond random polyphony on one piano, so it is far from Onsets and Frames or MT3. The quantizers see exact onsets; with a real transcription, its errors come first.
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- Hook: an ear question (performance or transcription?); Mozart and the Miserere; answer keys; the plan.
- One voice's pitch: the difference function; the missing fundamental; YIN's steps; the track as a sine, heard; uses.
- Pitch in noise: the sung Tune in three noises, tracked and heard; gross errors against noise; lessons.
- Many notes at once: why chords are hard; an ear question (the added octave); salience; cancellation; the hidden octave.
- Where notes begin: spectral flux; piano and strings, heard; precision against recall; what makes onsets hard.
- Factorizing the spectrogram: NMF and its updates; blind components; note templates; a piece factorized and re-played, heard; limits.
- A network that listens: design; training; results; inside; heard; how many notes at once.
- Timbres never heard: four instruments, heard; the scores; an ear question (the organ); why.
- Keeping score: precision, recall, F; an example; an ear question (missing notes or octave errors); frame scores; what keys contain.
- From notes to a score: seconds and beats; fixed-tempo and drifting-tempo quantization; the tempo curve; heard; key and spelling.
- Fifty years of transcription: early systems; data and benchmarks; the ear.
- Frontier: many instruments; audio to score; the research problem.
- Variation 61: the Tune performed, transcribed and re-rendered, five times round. Outro: problems, payoffs.
Covers: representations for pitch; autocorrelation and YIN; salience; onset detection; non-negative matrix
factorization and its updates; neural transcription; from notes to a readable score; evaluation.
Built and computed: monochord/mir/transcribe.py and neural.py: YIN (missing fundamental found at 220.0 Hz;
gross errors 9 % at 0 dB and 60 % at −5, where autocorrelation keeps 10 %); spectral-flux onsets (F 0.90 piano,
0.74 strings); NMF with piano templates (note F 0.49) and a small network (0.67), both scored on a harp, an organ
and strings they never heard (the network 0.24 on the harp); F against polyphony (0.91 to 0.54); quantization of
rubato with one tempo (1 of 14 onsets right) and with a drifting tempo (14 of 14); Part 15's key finder on the result.
Variation 61: the Tune performed, transcribed and re-rendered, five times round (note F 0.53 after one round,
0.10 after five).
Frontier: multi-instrument transcription (verify current results); score-level output.
Reading: Müller; de Cheveigné & Kawahara (2002); Smaragdis & Brown (2003); Benetos et al. (2019).
Build the film
python -m videos.music.music61.compute # the part's numbers, into .cache/music61
python tools/build.py music61 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py music61 Hook # one chapter, silent, with a contact sheet
Scenes: videos/music/music61. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
python -m videos.music.music61.compute # numbers and sounds (the network trains once)
EXPLAINER_TTS=silent python tools/build.py music61 -q l --fps 15 # a silent-narration preview, with the sounds
python tools/qa_sound.py music61 --sync # the sound gates
python tools/dead_air.py renders/music61_480p.mp4 --sound music61 # no empty screen; no sound over a still one
python tools/lecture_length.py music61 # 30 to 60 minutes, listening included
python tools/build.py music61 # 1080p30, narrated
python -m pytest -q tests/music # Monochord against its references; this part's claims and clips
python -m videos.music.labs 61 # the lab (writes a figure and a short WAV)