♪Music, Built

Act XI · Listening Machines

Part 62 of 68

Beat, Chords and Structure

Foundationsstarts at this level33 min of film13 chaptersprerequisites: Part 9, Part 18, Part 21, Part 43, Part 61

How does a machine find the beat, the chords and the form of a song, and follow a singer live?

An ear question hears the session with a click track 80 ms late and one on the beat. People entrain and predict, and prefer tempos near 120; the listeners these methods power. Novelty: spectral flux with its local mean removed, the drums alone against the band, other novelty functions and kinds of accent, and an autocorrelation tempogram bright at 100, 200 and 50 beats a minute. Tempo: the autocorrelation times a prior near 120 finds 100 on the session; a slow piece written at 50 is read at 100 with the prior and 50 without, heard with both click tracks; tempo in real performances. Beats: forty years of trackers; Ellis's dynamic programme, F 0.94 on the session; on a rubato piano performance the tracker misjudges the tempo (125 against 106) and reaches only 0.58; scoring at several levels. Downbeats: an ear question on where bar lines fall; the low band marks beats one and three but cannot say which is first; other meters. Chroma: folding octaves, the Tune's chroma heard, its relatives and uses, chord templates. Chords: templates frame by frame 44 per cent, an HMM 51, an HMM with Bach's transitions 76; the confusions run a fifth up (C as G, G as D), from each note's third partial. Time warping: a strict and a rubato performance heard and aligned (median 13 ms offline and online), the path read as a tempo curve, its origins in speech. Following: computer accompaniment since 1984; Monochord's follower tracking a freely sung Tune, its chords a median 96 ms from the voice; what human accompanists do. Structure: the whole Tune's self-similarity heard; Foote's novelty misses the sections because nothing in the texture changes; repetition finds a b c c a b, A B A, where mean chroma cannot; song forms. Covers: an ear question (which is not the Tune?), key-invariant DTW finding the transposition of five semitones; covers in the wild; how far annotators agree. Frontier: whose meter, joint models, listening live; a research problem on predictive accompaniment. Variation 62: the Tune sung freely and accompanied twice, deaf and listening.

What you need. Part 9 for meter and the grid; Part 15 for keys; Part 18 for the chorales' chord transitions; Part 21 for form and self-similarity; Part 43 for expressive timing; Part 61 for spectral flux. Autocorrelation, dynamic programming, hidden Markov models and the Viterbi algorithm, cosine similarity.

Ideas, mathematics and history
tempograms, beat tracking by dynamic programming, time warping and score following, chord recognition, structure from self-similarity
What we build, compute and hear
a beat tracker, an aligner and a chord recognizer; an accompanist that follows rubato

What you will be able to do

Foundations

  • Hear a click track 80 ms late against one on the beat, and the drums alone against the whole band.
  • Hear a tracker's clicks on a steady band and on rubato, a slow piece at two tempos, and where bar lines fall.
  • Hear a strict and a rubato performance aligned, a cover in another key, and a singer accompanied live.

Full course

  • Compute novelty, the autocorrelation tempogram and a prior-weighted tempo; track beats by dynamic programming.
  • Recognize chords from chroma by templates and by an HMM with a transition prior, decoded by Viterbi.
  • Align performances by offline and online DTW, and find form from novelty and from repetition.

Research

  • Build a predictive follower and measure how close to a human accompanist it can play, and where it fails.

Practice

  • Report tempo with its octave in doubt, score beats at the right and at any sensible level, fit a prior to the music.

Contents

Each chapter has a home level. Choose a track to see what to read and watch: Foundations 26 min · Full course 31 min · Research 33 min · Practice 31 min.

  1. 0Clapping alongFoundations3 min
  2. 1Where the beats might beFoundations3 min
  3. 2Tempo, and its octaveFoundations2 min
  4. 3Tracking the beatFoundations3 min
  5. 4Bars and downbeatsFoundations2 min
  6. 5ChromaFoundations3 min
  7. 6Recognizing chordsPractice3 min
  8. 7Time warpingFoundations3 min
  9. 8Following a soloistPractice3 min
  10. 9StructureFoundations3 min
  11. 10Covers, and how far people agreeFoundations2 min
  12. 11Frontier: expressive and non-Western meterResearch2 min
  13. Variation 62, 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.

Clapping alongFoundations3 min

A child can clap along to a song; for decades a program could not. First, your own sense of the beat. The session, twice, with a click track. In one the clicks are on the beat; in the other they are milliseconds late, less than a tenth of a second. Which is on the beat?

The second. In the first the clicks trail the drums by eighty milliseconds, and most listeners hear it at once: we are precise judges of the beat.

That precision is easy for people. A child can clap along to a song; for decades a program could not. And today's programs still tap at half or double speed, and lose their place in a rubato. These listeners run DJ software, practice apps, playlists and accompaniment systems. They all ask three questions: where is the beat, what is the chord, and where does the section change?

How do people do it? We do not wait for each beat: attention is entrained, like an oscillator locked to the pulse, as Edward Large and Mari Riess Jones described in 1999. Tapping along, people tap a few tens of milliseconds early: they predict the beat rather than react to it. Some studies report preferred tapping or movement rates near a hundred and twenty a minute, with substantial individual and contextual variation, Dirk Moelants found in 2002. Timing sensitivity depends on tempo, timbre, task and listener; eighty milliseconds is conspicuous in this example, while twenty can also be detectable. That is the scale on which the machines of this part are judged.

These listeners run things you may use. DJ software matches two songs' tempos and lines up their beats and bars automatically. Practice apps slow a song without changing its pitch, loop four bars and show the chords as they pass. Playlists are built by tempo, for running, dancing or sleep. And musicology measures the tempos, harmonies and forms of thousands of recordings at once. Each depends on the three answers being right, or right enough.

Here is the plan. Where the beats might be, and how fast they come. Tracking them, and finding the bar. Chroma, and chords in context. Time warping, and an accompanist that follows a singer. The form of a song, from its repetitions. And covers, and how far people agree.

1Where the beats might beFoundations3 min

What does a machine listen to when it looks for the beat?

A beat is not a sound. It is the pulse a listener taps, and it can fall in silence, inside a held note or a rest. But beats usually coincide with note starts, accents and chord changes. So machines start from Part 61's spectral flux, a curve that rises wherever something begins. Subtract its local mean, keep what sticks up, and you have the novelty curve.

Here is the novelty curve of Part 56's session playing the Tune's first two phrases. Kick, snare, hi-hat, bass, guitar, piano and voice all start things, and the curve is a forest of peaks. But the forest has a rhythm: the tallest peaks fall on the beats, every six tenths of a second, a hundred a minute.

Hear the drums alone, then the whole band, and compare their novelty curves. The drums give a clean, regular comb; the band adds peaks for every sung note and chord, between the beats as well as on them. Here both give the same tempo, a minute, but in music without drums, a string quartet or a solo voice, the clean comb is gone, and that is where trackers struggle.

Spectral flux is one choice among several. Energy is the simplest: good for drums, deaf to a change of chord at the same loudness. Spectral flux, Part 61's, hears a new note even under a sustained one. Phase deviation listens to the phase: a steady note's phase advances predictably, and a new note breaks the pattern. Band by band, the low band hears kick and bass, the high band the hi-hats, and each says something different about the meter. And networks now learn their own novelty from annotated beats.

What makes a beat feel strong? Music theorists name several kinds of accent. A dynamic accent: louder. An agogic accent: longer; a long note after short ones feels like a beat. A harmonic accent, where the chord changes. A melodic accent, at the top or bottom of a contour, or after a leap. Novelty curves see the first kind well and the others barely, which is part of why music without drums is hard to track.

How fast? Slide a six-second window along the novelty curve and correlate it with itself at every lag, as YIN did for pitch, but a thousand times slower. Each column is one window, each row a tempo. The brightest row is a hundred beats a minute. But the rows at two hundred, the eighth notes, and fifty, every second beat, are bright too: rhythm repeats at every level of its own hierarchy.

2Tempo, and its octaveFoundations2 min

Why do machines tap at double speed?

To choose one tempo, add up the autocorrelation over the whole passage. It has peaks at the beat and at its multiples and fractions: rhythm is a hierarchy. Something must choose a level. Listeners asked to tap along prefer tempos near a hundred and twenty a minute, so trackers multiply by a prior centred there. On the session, the product peaks at a hundred, the tempo it was played at.

Now a slow piece, written at fifty beats a minute, a chord every beat with eighth notes above. Hear it with clicks at the written tempo, then at the tempo the tracker found.

The tracker, leaning toward a hundred and twenty, chose : double time. With no prior it finds . Neither is simply wrong: many listeners would tap the eighth notes too. This is the tempo octave problem, and it is why trackers are scored at more than one metrical level.

And real tempos move. A live band drifts; a few beats a minute faster by the end of a song is common. Classical performers shape tempo on purpose, with the phrase arches and held cadences of Part 43. A click track removes drift, and much recorded pop since the 1980s is built on one. So a single tempo describes a recording only roughly; a tempo curve describes a performance.

This is not only a machine's problem. Asked to tap along, listeners split between levels, above all at slow and fast tempos. And a tempo is not one number for long: performers speed up, slow down and hold. So evaluations ask two questions: did the system find a beat at some sensible level, and did it find the one most listeners tap? The prior summarizes some listener studies; it is not a universal preferred tempo or a fact about the correct notated beat.

3Tracking the beatFoundations3 min

Where exactly does each beat fall?

Knowing the tempo, where exactly do the beats fall? A good beat sequence lands on strong novelty and keeps a steady period. Daniel Ellis wrote that as a score: the best total for a sequence ending at time t is the novelty there, plus the best total for a previous beat, less a penalty that grows as the gap departs from the period. Alpha sets how strict the period is. Compute it left to right, remember each best previous beat, and trace back from the end: dynamic programming, which tracks a whole song in a fraction of a second.

Beat tracking has a history of its own. In 1985 Dirk-Jan Povel and Peter Essens modelled which rhythms make a listener infer a clock. In 1998 Eric Scheirer tracked beats in audio with a bank of resonating comb filters. In 2001 Masataka Goto built a real-time tracker for music with and without drums, and Simon Dixon's BeatRoot ran competing agents, each a hypothesis about the beat. Ellis's dynamic programme came in 2007, and from 2016 recurrent networks tracked beats and downbeats together. Each step added prediction: from reacting to onsets toward expecting beats, as listeners do.

Here is the tracker on the session, with a click on every beat it found.

With drums marking every beat, it is right almost everywhere: an F-measure of within seventy milliseconds.

Now the Tune played on the piano with rubato: the beats stretch and shrink through each phrase, and the phrase ends are held. Hear the tracker's clicks.

The tracker even misjudges the tempo, a minute against a true average of , and with one period for the whole piece it drifts against the performer. A strict period loses the held notes; a loose one wanders after every ornament. The best setting here reaches an F-measure of . Expressive timing is where beat trackers still fail, and why accompaniment systems follow the score instead, as Chapter 8 does.

How are beat trackers scored? By F-measure within seventy milliseconds, against the beats as annotated. And allowing other levels: double time, half time and the off-beat. On the session the tracker matches the annotated level, as the numbers show. Continuity measures count the longest stretch tracked correctly, since a listener notices a slip at once. The evaluation exchange MIREX has compared systems this way every year since 2006. Report both: the right level, and any sensible one.

4Bars and downbeatsFoundations2 min

Which beat is beat one?

Your turn. The session with a click on every beat and a higher click every four, twice. In which do the high clicks mark the start of each bar?

The second. There the accent falls with the kick drum and the changes of chord. In the first it falls on the snare, the backbeat, and the bar feels as if it starts in the wrong place.

How might a machine know? One clue is low: the kick drum and the bass mark strong beats. Average the low band's novelty at each of the four places in the bar. Beats one and three are strong, two and four weak. That says the bar has two strong beats, not which one comes first; chord changes, phrase lengths and melody have to decide, and modern systems learn all of them together.

And bars come in more shapes than four-four. Duple and triple: a march in two, a waltz in three, their strong beats spaced differently. Compound meters: six-eight commonly groups six eighth-note subdivisions into two dotted-quarter beats, and is easily heard as three-four. Swing moves the off-beat late, about two thirds of the way through the beat, or less. Additive meters, like seven-eight as two plus two plus three, have beats of unequal length. A downbeat tracker must first know which of these it is hearing.

What tells a listener where the bar starts? Harmony changes on strong beats, bass notes land on beat one, and melodies end their phrases there. Meter is a hierarchy: beats within bars, bars within phrases. Downbeat trackers combine beat tracking with these cues, and since the 2010s networks trained on annotated songs do it all at once. They inherit their annotations' habits: four-four time, Western popular music, steady tempos. Chapter 11 returns to that.

5ChromaFoundations3 min

How can a spectrogram be folded into twelve notes?

For harmony the machine needs a different picture. Harmony cares about pitch classes, not octaves: C is C in any register. So fold the log-frequency spectrogram: add every C together, every C sharp, and so on up to B. Twelve numbers a frame: the chroma vector, Shepard's pitch helix from Part 6, flattened. Compress it, and normalize each frame, so that harmony counts more than loudness. One complication: partials leak. A C's third partial is a G and its fifth an E, so chroma blurs every note toward its own major triad.

Here is the chroma of the session playing the Tune's opening, with the voice loud and the chords quiet, as a singer hears it.

The chords, C, F and G, show as rows that change every two beats. But the voice is louder than the chords, and its notes light their own rows, one at a time: the chroma looks as much like a melody as like a harmony. That is the chord recognizer's difficulty.

Chroma has relatives. Takuya Fujishima's pitch class profile of 1999 was an influential early pitch-class-profile approach to chord recognition. Tuning matters: a band tuned thirty cents flat smears every bin, so systems estimate the tuning first and shift. Emilia Gómez's HPCP weights each peak and its harmonics; Meinard Müller's CENS smooths chroma for matching. Or the chroma can be learnt: a network trained to output the pitch classes of the notes, not of their partials.

The simplest recognizer matches templates. Each chord is a template with ones on its three pitch classes. Twenty-four triads, major and minor on every root, and one for no chord. In each frame, pick the template closest in angle to the chroma. But C major and A minor share two notes, and one melody note can tip the balance.

Chroma carries the rest of this part too. Part 15's key finder runs on chroma averaged over a passage. Chapters 7 and 10 align recordings and match covers by comparing chroma sequences. And Chapter 9's self-similarity is chroma against chroma. Chroma discards explicit register and much timbral detail; its time sequence still contains rhythmic timing and timbre can affect the estimates; for harmony, that is the point.

6Recognizing chordsPractice3 min

How does knowing what usually comes next help?

Listeners hear chords in context, and so can a machine. In a hidden Markov model the chord is hidden and the chroma observed. The probability of a chord sequence multiplies how well each chord's template fits its frame by how likely each chord is to follow the last. Mostly, frame to frame, a chord stays put. The Viterbi algorithm finds the most likely sequence by dynamic programming, as the beat tracker did. Monochord tries two priors: stay or move anywhere, and the transitions Part 18 counted in Bach's chorales, I to IV, IV to V, V to I.

Here are the three recognizers on four phrases of the session, against the chords played. Frame by frame, the templates flicker, fooled by the melody and the attacks: percent of frames right. An HMM that only knows chords tend to stay put smooths the flicker: percent. With Bach's transitions as the prior, the recognizer prefers transitions found in this selected major-key chorale corpus; that can help this Tune without being a universal grammar, and gets percent. Knowing what usually comes next is worth as much as listening harder.

Which mistakes does the frame-by-frame matcher make? Most often, C heard as G, and G heard as D: each chord mistaken for the chord a fifth above. Physics explains it. Every note's third partial is its fifth, an octave up, so the chroma of a C chord carries extra G, and leans toward G major. The rest are frames called no chord, where an attack or a loud sung note blurs everything. Context, in the HMM, repairs both kinds.

A prior is a bet. It helps where the evidence is weak, and misleads where the music breaks its habits. Bach's transitions suit the Tune; they would fight a blues, a modal folk song or a jazz standard. Modern recognizers learn both parts from data: networks for the evidence, sequence models for the prior. And they use a larger vocabulary, sevenths, inversions and suspensions, where annotators themselves start to disagree. Part 18's statistics, built to describe music, turn out to be what a listener, or a machine, uses to hear it.

7Time warpingFoundations3 min

How do you line up a score with a performance?

Here is the Tune with its chords played strictly, a beat every half second, then with rubato. Same notes, different times.

Aligning them means finding, for every moment of one, the matching moment of the other: these lines.

Dynamic time warping does it. Compare every chroma frame of one with every frame of the other: bright where they match. Then find the cheapest path from the start of both to the end of both, moving forward in one, the other or both at each step: dynamic programming, a third time. Offline, with both recordings whole, the path has a beat-alignment error of milliseconds, at the median. In the incremental path algorithm, given precomputed features, the median is milliseconds, with a worst moment of , at a held note where nothing new arrives.

The warping path is also a measurement. Its slope says how much longer each beat of the performance is than the same beat played strictly: a tempo curve. Read from the path, it follows the truth, beat by beat: the stretching through each phrase and the held phrase end, all but the very last beat, where the path runs out. Alignment can estimate timing curves from real recordings; Part 43's synthetic examples should not be mistaken for new measurements of real pianists, recording by recording.

Time warping came from speech. In 1978 Hiroaki Sakoe and Seibi Chiba matched a spoken word against stored examples, however fast or slow it was said. Its cost grows with the product of the two lengths: two three-minute recordings at twenty frames a second make thirteen million cells. So paths are kept in a band near the diagonal, or found coarse to fine. Music added chroma, and the knowledge that a performance never goes backwards, except for the repeats.

Alignment has many uses. Page turning: a tablet follows the pianist and turns the page. Study: line up fifty recordings of one sonata and compare their tempos bar by bar, as Part 43 did. Answer keys: align a score to a recording and you have its notes' times, which Part 61's transcribers need. Lyrics shown as they are sung. And the accompanist of the next chapter.

8Following a soloistPractice3 min

Can a machine accompany a singer who takes their own time?

Following a performer live is an old dream. In 1984 Roger Dannenberg and Barry Vercoe, separately, built computer accompanists that followed a soloist. A follower listens; an accompanist must also predict where the soloist will be, and play there. From the late 1990s Christopher Raphael's Music Plus One followed concerto soloists with a recorded orchestra. Latency is the enemy: the accompaniment has to sound with the note, not after hearing it.

Monochord's accompanist is the simplest that works. It hears the singer as chroma, frame by frame. Online time warping against the score says where the singer has got to. And when the score reaches a chord, it plays it, with an assumed sixty-millisecond extra delay; we have not measured a live callback. The chroma is precomputed with whole-recording normalization, so this is an incremental-alignment simulation rather than an end-to-end causal system. It does not predict; Chapter 11's research takes that up.

Here is the follower at work. The grey line is where the singer really is in the score, beat by beat, curving with the rubato. The gold line is where the follower believes the singer is. It climbs in steps, waiting for evidence, then catching up; it never goes backwards. Where the singer holds a note, nothing new arrives, and the follower waits too.

What do human accompanists do that this one does not? Ensemble players keep together within a few tens of milliseconds, by listening and predicting at once. They correct each other continuously, each adjusting to the other's last asynchrony, as Part 43's ensemble did. They read the soloist's body: a breath, a nod, a lifted bow, before the sound. And they know the music: where the soloist will slow, where they will hold. A machine that only listens starts every note behind; to play with a soloist, it must expect.

How close does it play? Each bar is one chord: how far it sounded from the singer's beat. Most land late, by the processing delay and the time it takes the follower to be sure: a median absolute timing error of milliseconds. One lands early, where the follower jumped ahead. Ensemble players keep within a few tens of milliseconds; this accompanist would sound a little behind. You will hear it in the Variation.

9StructureFoundations3 min

Can a machine hear the form of a song?

Hear the whole Tune by the session, and watch its self-similarity matrix: every moment compared with every other, bright where the chroma matches.

The bright diagonal is each moment matching itself. The stripes parallel to it are passages that repeat: the shape of the song, drawn by the song.

Jonathan Foote's method of 2000 slides a checkerboard along the diagonal and looks for places where the music before differs from the music after. On the Tune, its peaks are weak and land a beat or more away from the real section changes. The reason is honest: nothing in the texture changes. The same band plays the same chords throughout; the sections differ only in which tune they play.

Repetition finds it instead. Cut the Tune into its six phrases, eight beats each, using the known rendered tempo and eight-beat phrase length; phrase boundaries are supplied, not discovered by this step, and compare every pair moment by moment along the stripes. Phrases one and five match, two and six, and three and four: a b, c c, a b. That is A B A, the Tune's form. Averaged over each phrase, the chroma cannot tell them apart; the order of the notes is what distinguishes them.

What forms might a machine find? At this coarse level, the Tune's A B A, a form shared by some nursery songs and of a da capo aria. AABA, the thirty-two-bar chorus of Tin Pan Alley that Part 40 counted. Verse and chorus: the chorus returns with the same words, the verses with new words over the same music. A labeller built on repetition hears a verse's music come back, but not its new words; lyrics need another listener. The form a machine finds is the form its features can see.

In real songs the two cues work together: a chorus may be louder and fuller, though this is not a defining rule, which novelty sees, and it comes back, which repetition sees. Brian McFee and Daniel Ellis joined both in one graph in 2014 and found sections by spectral clustering. Structure also has levels: phrases within sections within the song. And people disagree about it, as the next chapter measures.

10Covers, and how far people agreeFoundations2 min

When are two recordings the same song?

Your turn. Three recordings. Two are versions of one song, in different keys, tempos and instruments. Which is the odd one out?

The third, Frère Jacques. The second was the Tune, a fourth higher and with rubato, on the piano. Easy for you; a machine has to be told that a key and a tempo are not the song.

The machine's version of your judgment: compare chroma sequences by time warping, which forgives the tempo, and try all twelve rotations of the chroma, which forgives the key. The cover's best rotation is semitones, the fourth it was transposed by, and its cost falls well below Frère Jacques's. Systems built this way searched thousands of recordings for covers in the 2000s; networks trained on cover pairs do it now.

Real covers are harder. A cover can change everything but the song: key, tempo, instruments, genre, even the structure. In 2011 the SecondHandSongs collection gave thousands of real cover pairs to test on. The uses are practical: tracking royalties for live performances, finding versions, and Part 60's questions of similarity. And where covers end and influence begins is a question for courts, not for time warping.

One more limit, for every chapter of this part. Every number here was scored against an answer key, and for real recordings people make the keys. Beats: annotators tap at different levels and disagree by tens of milliseconds. Chords: is that a C or a C major seventh, a passing chord or a new harmony? Structure: two experts' boundaries for the same song agree only in part; the SALAMI collection of 2011 has two annotations per song to show it. When people agree only so far, annotator disagreement measures ambiguity and protocol dependence, not an absolute accuracy ceiling; a system can agree better with a defined consensus than two individual annotators agree with each other. Monochord's renders have exact keys; real recordings require an explicit annotation convention and uncertainty.

11Frontier: expressive and non-Western meterResearch2 min

Whose beat is the machine listening for?

Two frontiers. The first is meter itself. Most annotated data is Western popular music in four-four at a steady tempo. These traditions include varied cyclic and metrical structures; some have equal subdivisions, while additive groupings can produce unequal beat lengths, which a four-four tracker misreads. Datasets of other traditions, Carnatic, Hindustani, Turkish makam, Afro-Cuban, exist and change the picture. And in expressive music, where a nocturne's tempo moves every bar, beat trackers still fail, as Chapter 3 found. The beat a machine hears is the beat its training data annotated.

The second is doing it all at once. Beats, downbeats, tempo, chords and sections depend on each other. Joint models predict them together, each helping the others: downbeats where chords change, sections at downbeats. And models trained on large unlabelled collections now supply features for all these tasks; check the current results. Monochord's renders can test them where the answer is exact.

A third frontier is time itself. Live listening is harder than listening to a file: there are no future frames, and a deadline every few milliseconds. A phone must track beats and chords as the music plays, for a light show, a game or a practice app. That needs causal models small enough to run on the device, with their latency measured, not assumed. Live, the measure that matters is both accuracy and end-to-end latency.

A research problem to end on, from Chapter 8. An accompanist must play with a note, not after it: it has to predict. Model a performer's timing: phrase arches, held phrase ends, the habits of Part 43's expressive performer. Predict each next beat's time from the past, with an uncertainty, and play there. The question: how close to a human accompanist can a predictive follower play, and on what music does it fail? An answer would decide when machines can join live ensembles.

Variation 62, recap and problemsAll tracks2 min

Every part ends by doing something to the Tune with what it built. Here Part 8's voice sings it freely, with rubato, and a piano accompanies twice: first playing its chords on the written beats, deaf to the singer; then placing each chord where the follower hears the singer has got to.

Row sixty-two of the ledger. The deaf piano drifts away from the singer as the rubato grows. The follower stays with them, a median milliseconds in absolute error; individual chords can be early or late: close enough to sound like accompaniment, late enough to sound like a careful one.

What did we find? Novelty curves show where things begin, and autocorrelation how often. A prior near a hundred and twenty picks the tempo's level, and sometimes the wrong one. Dynamic programming tracks beats, and rubato defeats a fixed period. Chroma folds the octaves, and an HMM with Bach's transitions hears chords in context. Time warping aligns performances, offline and live. And repetition finds a song's form where novelty cannot, while annotation choices shape how all these results are interpreted.

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 finding music, with beat-matched playlists and fingerprints. In source separation, where beats and chords guide the separator. In machines that compose, which need bars, chords and form. In research, with annotators and their disagreements. And in the concert at the end of the series.

And in practice. Report a tempo with its octave in doubt, and check by tapping. Score beats within seventy milliseconds, at the right level and at any sensible one. Give a chord recognizer a prior suited to the music, not Bach by default. And find structure with repetition and novelty together, against two annotators if you can.

The books and papers this part follows. The full list, with notes, is in the README.

Where it goes next. Beat-matched playlists and fingerprints in Part 63; beats and chords guiding separation in Part 64; bars, chords and form as structure for machines that compose in Part 65; annotators and their disagreements in Part 67; an accompanist that listens, in the concert of Part 68.

Key results

The part's results in one place, for revision.

Ellis's DP\(\displaystyle C(t) = O(t) + \max_\tau\big[C(\tau) - \alpha\log^2\tfrac{t - \tau}{P}\big]\)
Tempo prior\(\displaystyle \hat T = \arg\max_T\ \mathrm{AC}(T)\,\exp\!\big(-\tfrac12 (\log_2 T/120)^2/\sigma^2\big)\)
Viterbi\(\displaystyle \delta_t(j) = \max_i \delta_{t-1}(i)\,A_{ij}\,b_j(x_t)\)
DTW\(\displaystyle D(i, j) = c(i, j) + \min\{D(i{-}1, j{-}1), D(i{-}1, j), D(i, j{-}1)\}\)
Foote\(\displaystyle N(t) = \sum_{a,b} K(a, b)\,S(t + a, t + b)\)

Try it

Lab 62 · Beat, chords and structure, computed

Find the tempo of a drum pattern and track its beats, recognize a chord progression frame by frame and with an HMM, align a strict and a stretched performance by time warping, and find a piece's form from its repetitions.

Figure produced by Lab 62: Beat, chords and structure, computed
Produced by the lab below, seed 0, in 0.5 s.
python -m videos.music.labs 62 needs numpy, scipy, matplotlib · download lab62.py · source on GitHub
drums at 96: tempo found (prior 120)                              193.5
beats: F within 70 ms, at any level                               0.63, 0.96
chords right, frame by frame and with the HMM                     0.90, 0.95
alignment: chord starts placed within (median, worst)             11 ms, 45 ms
form from repetition (three four-chord phrases)                   a b a
ear problem: four click tracks; how late is each? (listen first)  40 ms, 0 ms, 20 ms, 80 ms

Novelty shows where things begin and autocorrelation how often; a prior picks the tempo's level; dynamic programming places the beats; chroma and an HMM hear chords in context; time warping aligns timings; repetition reveals form.
The code (113 lines; it asserts its own result)
"""Lab 62: beat, chords and structure, computed: tempo with a prior, Ellis's beat tracker, chords by templates and by
an HMM, time warping between two timings, and form from repetition, all on sounds whose answers are known."""

import numpy as np

from videos.coursekit import labs
from explainer.music.monochord import SR, Clip, concat
from explainer.music.monochord.mir import rhythm as RH
from explainer.music.monochord.partkit import organ_tone

TITLE = "Beat, chords and structure, computed"
GOAL = ("Find the tempo of a drum pattern and track its beats, recognize a chord progression frame by frame and with an "
        "HMM, align a strict and a stretched performance by time warping, and find a piece's form from its repetitions.")
TASKS = [
    "Change BPM and PRIOR. When does the tracker report double or half the tempo?",
    "Change SELF (the HMM's chance of staying on a chord). What happens to the chord flicker, and to fast changes?",
    "Change STRETCH (how unevenly the second performance is timed). How large can it get before the alignment fails?",
]
BPM, PRIOR = 96.0, 120.0
SELF = 0.9
STRETCH = 0.25


def drums(seconds, bpm, seed=0):
    rng = np.random.default_rng(seed)
    x = np.zeros(int(seconds * SR))
    beat = 60.0 / bpm
    n = int(0.06 * SR)
    for k in range(int(seconds / beat)):
        g = 1.0 if k % 2 == 0 else 0.7
        burst = rng.standard_normal(n) * np.exp(-np.arange(n) / ((0.03 if k % 2 == 0 else 0.012) * SR)) * g
        i = int(k * beat * SR)
        x[i:i + n] += burst[: len(x) - i]
        j = int((k + 0.5) * beat * SR)
        if j + n // 3 < len(x):
            x[j:j + n // 3] += 0.25 * rng.standard_normal(n // 3) * np.exp(-np.arange(n // 3) / (0.004 * SR))
    return x / np.max(np.abs(x)) * 0.8, np.arange(int(seconds / beat)) * beat


def chords(prog, beat=0.5, times=None):
    out = []
    for k, (r, minor) in enumerate(prog):
        d = beat * 2 if times is None else times[k + 1] - times[k]
        out.append(sum(organ_tone(261.63 * 2 ** (t / 12), d, partials=5) for t in (r, r + (3 if minor else 4), r + 7)))
    y = np.concatenate(out)
    return y / np.max(np.abs(y)) * 0.8


def run(seed=0):
    rng = np.random.default_rng(seed)
    lab = labs.Lab()
    x, beats = drums(12.0, BPM, seed)
    nv = RH.novelty(x)
    tp = RH.tempo(nv["nov"], nv["hop_s"], prior_bpm=PRIOR)
    est = RH.track_beats(nv["nov"], nv["hop_s"], tp["bpm"])
    sc = RH.beat_scores(beats, est)
    lab.row(f"drums at {BPM:g}: tempo found (prior {PRIOR:g})", f"{tp['bpm']:.1f}")
    lab.row("beats: F within 70 ms, at any level", f"{sc['f']:.2f}, {sc['any_level']:.2f}")
    assert sc["any_level"] > 0.8
    prog = [(0, False), (9, True), (5, False), (7, False)] * 2
    y = chords(prog)
    C = RH.chroma(y)
    A = np.full((25, 25), (1 - SELF) / 24)
    np.fill_diagonal(A, SELF)
    res = RH.recognize(C["C"], A=A)
    labels = RH.chord_labels()
    n = C["C"].shape[1]
    truth = np.array([(r + (12 if m else 0)) for r, m in prog])[np.minimum((np.arange(n) * C["hop_s"] / 1.0).astype(int), len(prog) - 1)]
    lab.row("chords right, frame by frame and with the HMM", f"{np.mean(res['frame'] == truth):.2f}, {np.mean(res['hmm'] == truth):.2f}")
    assert np.mean(res["hmm"] == truth) >= np.mean(res["frame"] == truth) - 0.05
    times = np.r_[0, np.cumsum(1.0 * (1 + STRETCH * np.sin(np.arange(len(prog)) * 1.3)))]
    y2 = chords(prog, times=times)
    d = RH.dtw(RH.chroma(y, hop=2400)["C"], RH.chroma(y2, hop=2400)["C"])
    hop = 2400 / SR
    pt = d["path"] * hop
    found = [pt[np.abs(pt[:, 0] - k * 1.0) <= hop, 1].mean() for k in range(len(prog))]
    err = np.abs(np.array(found) - times[: len(prog)])
    lab.row("alignment: chord starts placed within (median, worst)", f"{1000 * np.median(err):.0f} ms, {1000 * np.max(err):.0f} ms")
    form = [(0, False), (5, False), (7, False), (0, False)]
    piece = chords(form + [(9, True), (2, True), (7, False), (7, False)] + form)
    S = RH.ssm(RH.chroma(piece, hop=2400)["C"])
    L = int(round(4.0 / hop))
    M = RH.segment_similarity(S, L, 3)
    form_found = RH.labels_from_similarity(M, 0.95)
    lab.row("form from repetition (three four-chord phrases)", " ".join(form_found))
    assert form_found == ["a", "b", "a"]
    # the ear problem: the drums with a click track early, on time or late
    shifts = list(rng.permutation([0, 20, 40, 80]))
    clips = []
    for sft in shifts:
        y3 = x[: int(6 * SR)].copy()
        nclick = int(0.015 * SR)
        burst = np.sin(2 * np.pi * 2500 * np.arange(nclick) / SR) * np.exp(-np.arange(nclick) / (0.003 * SR)) * 0.4
        for b in beats[beats < 5.8]:
            i = int((b + sft / 1000) * SR)
            y3[i:i + nclick] += burst[: len(y3) - i]
        clips.append(Clip(y3, SR))
    lab.audio = concat(clips, gap=0.8)
    lab.row("ear problem: four click tracks; how late is each? (listen first)", ", ".join(f"{s} ms" for s in shifts))
    fig, (ax1, ax2) = labs.figure(2)
    ax1.plot(nv["t"], nv["nov"], color=labs.GOLD, lw=0.8)
    for b in est:
        ax1.axvline(b, color="0.5", lw=0.5)
    ax1.set_xlabel("s")
    ax1.set_ylabel("novelty and beats")
    ax2.imshow(S, origin="lower", cmap="magma", aspect="auto")
    ax2.set_xlabel("frame")
    ax2.set_ylabel("frame")
    lab.fig = fig
    lab.note = ("Novelty shows where things begin and autocorrelation how often; a prior picks the tempo's level; dynamic "
                "programming places the beats; chroma and an HMM hear chords in context; time warping aligns timings; "
                "repetition reveals form.")
    return lab

Now change it

  1. Change BPM and PRIOR. When does the tracker report double or half the tempo?
  2. Change SELF (the HMM's chance of staying on a chord). What happens to the chord flicker, and to fast changes?
  3. Change STRETCH (how unevenly the second performance is timed). How large can it get before the alignment fails?

Problems, with solutions

Try each problem before opening its solution.

  1. Compute. A tracker's beats are each 50 ms late. Within a 70 ms tolerance, what is its F-measure? And if they are 80 ms late?

    Solution

    At 50 ms every estimate is within tolerance of its reference beat: precision and recall are 1, F = 1. At 80 ms none is (each is 80 ms from one beat and, at any tempo slower than about 400 a minute, further from the next): F = 0. The tolerance turns a small shift into all or nothing, which is why continuity measures are reported too.

  2. Prove. Show that the Viterbi recursion finds the most likely state sequence of an HMM, by induction on the frame.

    Solution

    Let δ_t(j) be the largest probability of any state sequence ending in j at frame t, jointly with the observations so far. For t = 1, δ_1(j) = π_j b_j(x_1). Any sequence ending in j at t + 1 passes through some i at t, and its probability factors as (its first t states' joint probability) × A_ij × b_j(x_{t+1}); the first factor is at most δ_t(i), with equality for the best sequence to i. So δ_{t+1}(j) = max_i δ_t(i) A_ij b_j(x_{t+1}), and following the maximizing i back from the best final state recovers the most likely sequence.

  3. Ear. The lab plays a drum pattern with click tracks shifted by random amounts; which are late? Find your threshold.

    Solution

    The lab prints the shifts. Most listeners hear 40 ms as slightly late and 80 ms as clearly so; 20 ms is near the threshold for clicks against drums.

  4. Build. Add a tempo that drifts to the beat tracker: let the period itself be a hidden state.

    Where to look. Replace the fixed P in the DP by a state (time, period) with transitions that change the period by at most a few percent a beat; score with the same novelty and log-ratio penalty; the search grows by the number of periods allowed. Test on the rubato performance of Chapter 3.

  5. ★ How close to a human accompanist can a predictive follower play, and on what music does it fail?

    Where the frontier is. Model the soloist's timing (phrase arches, held cadences), predict each next beat with an uncertainty, schedule the accompaniment ahead of it, and compare asynchronies with human duos on the same music, by style and tempo.

Notes and sources

Sources

  • M. Müller, Fundamentals of Music Processing (2nd ed., 2021); A. Lerch, An Introduction to Audio Content Analysis (2nd ed., 2022).
  • E. W. Large and M. R. Jones, "The dynamics of attending", Psychological Review (1999); D. Moelants, "Preferred tempo reconsidered" (ICMPC, 2002); B. H. Repp, "Sensorimotor synchronization: a review of the tapping literature", Psychonomic Bulletin & Review (2005).
  • D.-J. Povel and P. Essens, "Perception of temporal patterns", Music Perception (1985); E. D. Scheirer, "Tempo and beat analysis of acoustic musical signals", JASA (1998); M. Goto, "An audio-based real-time beat tracking system", JNMR (2001); S. Dixon, "Automatic extraction of tempo and beat from expressive performances", JNMR (2001); D. P. W. Ellis, "Beat tracking by dynamic programming", JNMR (2007); S. Böck, F. Krebs and G. Widmer, "Joint beat and downbeat tracking with recurrent neural networks" (ISMIR, 2016).
  • T. Fujishima, "Realtime chord recognition of musical sound" (ICMC, 1999); A. Sheh and D. P. W. Ellis, "Chord segmentation and recognition using EM-trained hidden Markov models" (ISMIR, 2003); E. Gómez, Tonal description of music audio signals (thesis, 2006); M. Müller, F. Kurth and M. Clausen, "Audio matching via chroma-based statistical features" (ISMIR, 2005).
  • H. Sakoe and S. Chiba, "Dynamic programming algorithm optimization for spoken word recognition", IEEE Trans. ASSP (1978); S. Dixon, "Live tracking of musical performances using on-line time warping" (DAFx, 2005); R. B. Dannenberg, "An on-line algorithm for real-time accompaniment" (ICMC, 1984); B. Vercoe, "The synthetic performer in the context of live performance" (ICMC, 1984); R. B. Dannenberg and C. Raphael, "Music score alignment and computer accompaniment", CACM (2006).
  • J. Foote, "Automatic audio segmentation using a measure of audio novelty" (ICME, 2000); B. McFee and D. P. W. Ellis, "Analyzing song structure with spectral clustering" (ISMIR, 2014); J. B. L. Smith et al., "Design and creation of a large-scale database of structural annotations" (SALAMI, ISMIR, 2011).

The follower is a simulation on precomputed chroma with global normalization and an assumed 60 ms added delay, not a measured causal audio implementation. Its reported median error is absolute. The form demo supplies the known tempo and eight-beat phrase segmentation. Annotator disagreement is not an absolute performance ceiling.

About this partfrom its README

Part 62 of a sixty-eight-part course in music (see the series plan and the syllabus), the second part of Act XI, Listening Machines. A child can clap along to a song; for decades a program could not, and today's programs still tap at half or double speed and lose their place in a rubato. This part builds the listeners that make DJ software, practice apps and accompaniment systems work: novelty and tempo, beat tracking by dynamic programming, downbeats, chroma and chord recognition with Part 18's chorale statistics as the prior, dynamic time warping offline and live, and form from self-similarity and repetition. The tools are Monochord's (explainer/music/monochord/mir/rhythm.py, on Part 61's spectral flux); every performance is rendered by Monochord, so every beat, chord and section is known exactly.

  • Clapping along. An ear question (the session with a click track 80 ms late and one on the beat: which is on the beat? the second); how people hear the beat (entrainment, tapping ahead, a preferred tempo near 120); clapping along; what these listeners run; the plan.
  • 1. Where the beats might be. What to listen for; the session's novelty curve; the drums alone against the whole band, heard; other novelty curves; what makes a beat strong; a tempogram (bright at 100, 200 and 50).
  • 2. Tempo, and its octave. Choosing one tempo (the autocorrelation times a prior near 120: 100 on the session); a slow piece written at 50, read at 100 with the prior and 50 without, heard with both click tracks; tempo in real performances; which level.
  • 3. Tracking the beat. Ellis's dynamic programme; forty years of beat trackers; the session tracked (F 0.94), heard; a rubato piano performance tracked (the tempo misjudged at 125 against 106; F at best 0.58), heard; scoring beats.
  • 4. Bars and downbeats. An ear question (where do the bars start? the second); a clue in the bass (beats one and three strong, but not which is first); other meters; what tells us where the bar starts.
  • 5. Chroma. Folding octaves; chroma's relatives; the Tune's chroma, heard; chord templates; what else chroma is for.
  • 6. Recognizing chords. Chords in context (an HMM, Viterbi, two priors); the three recognizers compared (44 %, 51 % and 76 % of frames right); what the frame-by-frame matcher confuses (chords heard a fifth up); what a prior does.
  • 7. Time warping. One score, two timings, heard; dynamic time warping (median 13 ms offline, 13 ms online, 206 ms at worst live); a tempo curve from the path; where time warping came from; what alignment is for.
  • 8. Following a soloist. Computer accompaniment (Dannenberg and Vercoe, 1984; Raphael); Monochord's accompanist; the follower following; what human accompanists do; how close it plays (a median 96 ms behind the voice).
  • 9. Structure. The whole Tune against itself, heard; Foote's novelty (weak, misplaced peaks: nothing in the texture changes); repetition (phrases a b c c a b: A B A; mean chroma cannot tell them apart); forms a machine might find; structure in practice.
  • 10. Covers, and how far people agree. An ear question (which is not the Tune? the third, Frère Jacques); key-invariant matching (the cover found five semitones up); covers in the wild; how far people agree.
  • 11. Frontier: expressive and non-Western meter. Whose meter; joint models; listening live; ★ research problem: how close to a human accompanist can a predictive follower play, and on what music does it fail?
  • Variation 62, recap and problems. The Tune sung freely by Part 8's voice, accompanied by a piano that ignores it, then by one that listens; the ledger; what we found; five problems; where it comes back; in practice; references; Part 63.
What is computed and built

python -m videos.music.music62.compute (about a minute) fills .cache/music62/.

Item What it computes Checked against
hook, drums, tempo, halfdouble click tracks; novelty; the tempogram; prior-weighted tempo the tempo played (tests)
beats, downbeat Ellis's tracker on the session and on rubato; the low band by bar position the beats rendered (tests)
chords chroma; templates, an HMM, an HMM with Bach's transitions; confusions the chords played (tests)
align, follow offline and online DTW; the path's tempo curve; a live accompanist the beat times rendered (tests)
structure, cover self-similarity, Foote's novelty, repetition; key-invariant DTW the sections and the transposition (tests)

Monochord's tools are held in tests/music/test_rhythm.py; this part's claims and clips in tests/music/test_music62.py.

Sounds. Part 56's session, Part 38's piano (strict, with rubato, and a slow piece), Part 8's voice, Part 40's kit.

What the models are, and are not. The beat tracker is Ellis's (2007) with a fixed period from one tempo estimate; real systems track a changing tempo. The chord recognizer has 24 triads and "no chord", a cosine emission and a hand-set stay probability; the Bach prior is Part 18's Roman-numeral bigrams mapped to C major, so it is right only for music in C. The follower is causal DTW with no prediction, and its 60 ms processing delay is assumed. The structure labeller uses phrase lengths from the beat tracker and a fixed threshold.

Companion material in this repository

The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
  1. Hook: an ear question (which click track is on the beat?); how people hear the beat; clapping along; what these listeners run; the plan.
  2. Where the beats might be: what to listen for; the novelty curve; drums and band, heard; other novelty curves; accents; a tempogram.
  3. Tempo, and its octave: choosing one tempo with a prior; a slow piece at two tempos, heard; tempo in real performances; which level.
  4. Tracking the beat: Ellis's dynamic programme; forty years of trackers; the session and a rubato performance tracked, heard; scoring.
  5. Bars and downbeats: an ear question (where do the bars start?); a clue in the bass; other meters; cues.
  6. Chroma: folding octaves; relatives; the Tune's chroma, heard; templates; uses.
  7. Recognizing chords: an HMM and Viterbi; three recognizers compared; confusions a fifth up; what a prior does.
  8. Time warping: one score, two timings, heard; DTW offline and online; a tempo curve from the path; origins; uses.
  9. Following a soloist: computer accompaniment; Monochord's accompanist; the follower following; human accompanists; asynchrony.
  10. Structure: self-similarity, heard; Foote's novelty; repetition (A B A); forms; structure in practice.
  11. Covers, and how far people agree: an ear question (which is not the Tune?); key-invariant matching; covers in the wild; annotator agreement.
  12. Frontier: whose meter; joint models; listening live; the research problem.
  13. Variation 62: the Tune sung freely and accompanied, deaf and listening. Outro: problems, payoffs.

Covers: novelty curves and tempograms; beat tracking by dynamic programming; downbeats; time warping and score following; chroma; chord recognition with a hidden Markov model (Part 18's matrix as the prior); structure by self-similarity and repetition; cover-song detection; annotator disagreement as a ceiling. Built and computed: monochord/mir/rhythm.py: tempo with a prior (100 found on the session; a slow piece at 50 read at 100); Ellis's beat tracker (F 0.94 on the session, 0.58 at best on rubato); chords by templates, an HMM and an HMM with Bach's transitions (44, 51 and 76 % of frames); DTW alignment (median 13 ms offline and online) and a live accompanist (a median 96 ms behind the voice); structure from repetition (A B A) where novelty fails; key-invariant cover matching. Variation 62: the Tune sung freely, accompanied by a piano that ignores the singer, then by one that listens. Frontier: expressive and non-Western meter; joint models; live, on-device listening (verify). Reading: Müller; Ellis (2007); McFee & Ellis (2014); Dannenberg & Raphael (2006).

Build the film

python -m videos.music.music62.compute        # the part's numbers, into .cache/music62
python tools/build.py music62                  # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py music62 Hook   # one chapter, silent, with a contact sheet

Scenes: videos/music/music62. Setup: see the course page. Source of these notes: the README and the scenes' narration.

Build it
python -m videos.music.music62.compute                          # numbers and sounds (about a minute)
EXPLAINER_TTS=silent python tools/build.py music62 -q l --fps 15   # a silent-narration preview, with the sounds
python tools/qa_sound.py music62 --sync                         # the sound gates
python tools/dead_air.py renders/music62_480p.mp4 --sound music62  # no empty screen; no sound over a still one
python tools/lecture_length.py music62                          # 30 to 60 minutes, listening included
python tools/build.py music62                                   # 1080p30, narrated
python -m pytest -q tests/music                                 # Monochord against its references; this part's claims and clips
python -m videos.music.labs 62                                  # the lab (writes a figure and a short WAV)