♪Music, Built

Act XI · Listening Machines

Part 63 of 68

Finding Music

Foundationsstarts at this level35 min of film13 chaptersprerequisites: Part 2, Part 4, Part 58, Part 60, Part 61

How does a phone name a song from five noisy seconds, and how does a service choose what you hear next?

Five seconds of Variation 40 in a simulated bar, the music no louder than the noise, named with its offset among every sound of Parts 1 to 60 (908 clips, 3.7 hours, 1.15 million hashes); Shazam's phone number in 2002. A constellation of spectrogram peaks, about twenty a second, heard alone. Pairs of peaks as 24-bit hashes; votes for a clip and an offset; a match drawn as dots on one diagonal, the Tune's repeats on shorter ones. Noise: one query in three bars, heard; white noise is easier than bar noise (61 per cent named at 0 dB, 25 at -5); query length (9 per cent at one second, 81 at eight), heard; an ear question on a 16 kbit/s codec; the Poisson arithmetic of chance, and a hundred million tracks. Recordings, not songs: the Tune rendered afresh gets a tenth of a true excerpt's votes; an ear question on a Variation 4 per cent fast (lost: 59 per cent at 1 per cent, 25 at 2); a sample 12 dB under another track found 47 per cent of the time; a hummed query, slower, higher and out of tune, missed by the fingerprint and found first of 30 melodies by its pitch contour and time warping. Tags and embeddings: all 908 clips on two principal components, the acts overlapping (it knows sound, not subject); an ear question on nearest and farthest neighbours; GTZAN's faults. A horse: a classifier scores 83 per cent from a faint mains hum, 43 without it, and 48 trained honestly and split by clip, no better than guessing; its weight on the lowest bands. Collaborative filtering on simulated listeners: the play matrix and its factors; implicit ALS (recall at 10: 0.127 against 0.077 for popularity and 0.038 at random); the cold start from content (0.28 against 0.17). Popularity feeding on itself: Gini 0.97 after thirty rounds, 0.71 exploring, 0.13 without a recommender; Lorenz curves. Playlists by nearest neighbour and 2-opt (226 against 439), an ear question, the path on the map; fairness and metadata. Frontier: foundation models; effects on creators and the shrinking introduction; a research problem on what recommenders caused. Variation 63: three earlier Variations named through a bar's noise.

What you need. Part 2 for spectra; Part 4 for hearing in noise; Part 58 for codecs; Part 60 for streaming's money; Part 61 for pitch tracking. Hash tables, the Poisson distribution, principal components, logistic regression, alternating least squares, dynamic time warping, the travelling-salesman heuristic 2-opt.

Ideas, mathematics and history
Shazam's constellations, tagging and embeddings, the faults of GTZAN, collaborative filtering, cold start, popularity feedback
What we build, compute and hear
a fingerprinter over the whole series; a recommender on listeners whose tastes we know

What you will be able to do

Foundations

  • Hear a query in a noisy bar named, a codec, a query played fast, a sample buried in another track and a hummed tune.
  • Hear neighbours and the farthest clip by content, a mains hum a classifier learnt, and a random against an ordered playlist.
  • Explain why a fingerprint names a recording and not a song, and why popularity feeds on itself.

Full course

  • Fingerprint audio by spectrogram peaks and hashes, index it, and name queries by aligned votes.
  • Compute the chance of a false match from the Poisson tail, for any library size.
  • Factorize implicit feedback by ALS, score recall at k, and handle the cold start from content.

Research

  • Design a simulation of listeners, artists and a recommender, fitted to observable trends, to ask what recommenders caused.

Practice

  • Split data by recording and source, test with interventions, and check what a model's weights rely on before trusting a score.

Contents

Each chapter has a home level. Choose a track to see what to read and watch: Foundations 27 min · Full course 32 min · Research 35 min · Practice 32 min.

  1. 0A song from a noisy barFoundations2 min
  2. 1A constellation of peaksFoundations1 min
  3. 2Hashes and votesFoundations3 min
  4. 3Noise, codecs and chanceFoundations4 min
  5. 4Recordings, not songsFoundations4 min
  6. 5Tags and embeddingsFoundations3 min
  7. 6Right for the wrong reasonsFoundations3 min
  8. 7Learning from listeningPractice3 min
  9. 8Cold start and exploringFoundations2 min
  10. 9Popularity feeding on itselfPractice2 min
  11. 10Playlists, fairness and metadataFoundations3 min
  12. 11Frontier: foundation models and creatorsResearch3 min
  13. Variation 63, 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.

A song from a noisy barFoundations2 min

Five seconds of music in a noisy bar, the music no louder than the voices and glasses around it. Can a machine say what it is?

It can. Monochord's fingerprinter names the Variation, and the moment in it, among the locally available cached sounds from Parts 1 to 60, clips, in a fraction of a second.

The idea is old enough to have been a phone call. In 2002 in London you could dial two-five-eight-oh, hold your phone up to the music, and get the song's name back in a text message. The company, Shazam, was founded in 1999; Avery Wang described its search in 2003, and Apple bought it in 2018. Ten bad seconds, millions of recordings, an answer in seconds: from spectrogram peaks and a hash table. The same idea polices uploads: YouTube's Content ID has compared eligible uploads against participating rights holders' reference files since its 2007 introduction. And then the harder question: not which song is this, but which should come next?

Here is the plan. Fingerprints: peaks, hashes and votes. What noise, codecs and chance do to them, and why they find recordings, not songs. Tags and embeddings, and a classifier right for the wrong reasons. Learning from what people play. New songs nobody has played, exploring, and popularity feeding on itself. And playlists, fairness and metadata.

1A constellation of peaksFoundations1 min

What part of a recording survives a noisy bar? A fingerprint must survive noise, a phone's microphone, a codec and a room. Most of a spectrogram does not: the quiet detail is buried first. What survives is the loudest point in each neighbourhood of time and frequency, a local peak, because noise has to be louder than the music there to move it. So keep only the peaks' positions, and forget their heights: Wang called the result a constellation.

Here are eight seconds of a Variation, resampled to eight kilohertz for this fingerprint implementation. And its constellation: about peaks a second, each the loudest point in its neighbourhood. That is all the fingerprinter keeps.

Hear the recording, and then only its peaks, each played as a short sine at its frequency: the song as the fingerprinter hears it.

A sparkle of beeps, in which the melody can just be followed. Little enough to search fast; enough to distinguish many recordings when sufficient peaks survive.

2Hashes and votesFoundations3 min

How do ten seconds find their place among millions?

A single peak says little: a frequency at a time. Wang's trick is to pair them. Take each peak as an anchor, and pair it with a few later peaks in a zone ahead of it. Each pair becomes a hash: the two frequencies and the time between them, packed into twenty-four bits, one of sixteen million possible values. It does not depend on when the query started, only on the music's own intervals of time and frequency. Store it with the anchor's time.

Then index the library. Monochord's library contains the available cached clips of Parts 1 to 60: clips, hours of sound. That makes hashes, each stored under its value with the clip and the time it came from. Hash-table lookup has approximately constant average cost, while reading all postings and aggregating votes also takes time; that is what a hash table is for. A commercial service holds tens of millions of recordings and billions of hashes, spread over many machines.

The search is a vote. Look up each of the query's hashes; every hit is a vote for a clip and an offset, the clip's time minus the query's. For the right clip the votes pile up at a single offset, because the query's peaks keep their spacing. Chance hits scatter over clips and offsets. In the noisy bar, the right Variation collected votes at one offset, and the runner-up .

Here is what the votes look like, for five seconds of a Variation with the music level with a bar's noise. Each dot is one hash the query shares with a clip: its time in the query across, its time in the clip up. For the right clip, of the dots fall on one diagonal line, starting seconds into the clip: that line is the offset, and the excerpt's place in the recording. The shorter lines above it are the Tune repeating later in the same Variation. For the runner-up, dots scatter with no line to speak of. Counting dots on the best line is the whole search.

3Noise, codecs and chanceFoundations4 min

How much can go wrong before the answer does?

Hear one five-second query in three bars: the music ten decibels above the noise, level with it, and five decibels below.

And what the fingerprinter made of each: named twice, then lost when the bar drowns the music, as more of the peaks it needs are buried or moved.

Now count, over queries taken from the Variations. With bar noise, the fingerprinter names percent at ten decibels, percent with the music level with the noise, and percent five decibels below. White noise at the same level is easier: it spreads its energy evenly and thinly, while the bar's voices and glasses make peaks of their own, which compete with the music's. of the Variations reuse sound from another clip of their part; finding that clip counts as right.

How long must you hold up the phone? With the music level with the bar's noise, one second names the Variation per cent of the time; five seconds, per cent; eight, . Five decibels further down, eight seconds manage only per cent. Every second adds peaks, and every peak a chance for some hashes to survive the noise; which is why the app keeps listening until the votes are clear, rather than for a fixed time.

Hear one query both ways: Variation 7, level with the bar's noise, for one second, then for eight.

One second gives votes, for the wrong clip; eight seconds, for the right one: not many, but enough to come first. The tune is there in both to the ear; the machine needs the longer one.

Your turn. The same five seconds, twice: once as stored, once through Part 58's coder at sixteen kilobits. Which was coded?

The first was coded: duller and a little watery. But the peaks survive a codec, which is built to keep the loudest parts of the spectrum: the fingerprinter names almost every coded query, even at sixteen kilobits.

And when the music is not in the library at all, does the system invent an answer? Under an ideal uniform independent model, a random hash matches a given stored hash with probability two to the minus twenty-four. A query's few hundred hashes against stored ones give the expected number of chance hits in that model. But they scatter over every clip and every offset. Queries of pure noise collect at most votes in any one place; true matches collect or more. These finite noise trials suggest a useful threshold here; they do not establish a production false-positive rate: Part 60's birthday problem, kept in check by demanding agreement in time.

A real service holds a hundred million tracks, not nine hundred clips. Does chance catch up? The stored hashes grow from millions to more than a trillion, and a query's chance hits from hundreds to tens of millions. But they still scatter over every track and every offset. The Poisson union bound for at least three hits somewhere rises from about one in million to about one in ; six stays below one in ten to the sixteen. A true match, with dozens of votes in one place, stands far above that, in this independent uniform approximation. Real hashes are correlated, repeated music creates structured collisions, and searching more candidates increases opportunities for errors. Scale affects threshold calibration as well as memory and speed.

4Recordings, not songsFoundations4 min

Does a fingerprint know the song, or only the recording?

Here is the Tune, the song this whole series is built on, rendered afresh on the piano at a tempo no earlier part used. The library holds dozens of recordings of this song. Does the fingerprinter know it?

Not as a recording. Its best guess, , collects votes: more than chance, which in our finite trials gave pure noise no more than , because a few notes and chords sound alike in both; but a tenth of the or more that a true excerpt collects. A fingerprint identifies a recording, its exact peaks at their exact times. A new performance of the same song, at another tempo, can move many peaks enough to change these hashes.

Your turn. The same five seconds of a Variation, first as the library stores it, then played four per cent fast, as a radio station sometimes does. Will the fingerprint still name it?

It does not. Played as stored, the right clip gets votes; four per cent fast, the best any clip gets is , and it is the wrong one. Across all the Variations: half a per cent fast still works per cent of the time, one per cent , two per cent . Every peak moves up in frequency and closer in time, so the hashes change, though no listener would call it a different song. Fingerprints that survive speed changes exist, built on ratios of frequencies and of times, at some cost in speed.

A harder search, the one a rights service must make: find a recording used as a sample inside another track. Hear five seconds of Variation 3, then the same five seconds twelve decibels under Variation 10.

The search names Variation 10, with votes, and its copies elsewhere in the series; Variation 3 is not among the top five. Across all the Variations, a sample level with the track on top is found per cent of the time; six decibels down, ; twelve down, ; eighteen down, . The louder track's peaks bury the sample's. Quiet samples are the hard case for anyone who polices them.

To find the song rather than the recording, search by melody. Here is a hummed query: the Tune's opening, sung slower, three semitones higher, and a little out of tune.

The fingerprint finds nothing: its best guess collects votes, where a true match collects hundreds. A melody search instead tracks the query's pitch, with Part 61's YIN, and centres it so that the key does not matter. Then it compares that contour with each melody it knows, by time warping, which forgives the tempo. Among melodies, the Tune comes first, with a warping cost of , half the runner-up's . Services that search by humming rest on the same idea, with millions of melodies and faster indexes.

This is a feature, not a flaw. Fingerprints answer which recording: by matching signal details, quickly when the index is suitable. Which song needs Part 62's cover matching, using transposition comparisons and restricted time warping: slower, and less sure. Songs like this one needs features of sound and style, the subject of the next chapters. And the difference matters for money: a re-upload and a cover carry different rights, as Part 60 explained. Three questions, three kinds of similarity: the same signal, the same composition, the same taste.

5Tags and embeddingsFoundations3 min

How does a machine describe what music sounds like?

To find music by what it sounds like, it must be described. With tags: genre, mood, instruments, tempo, good for running. From people: Pandora's Music Genome Project, begun in 2000, had analysts score each song on hundreds of attributes. From crowds: listeners' free tags, plentiful and noisy. And from machines: a classifier trained on tagged audio predicts tags for everything else. Tags make music searchable by description, and recommendable before anyone has played it.

Tags are words; machines prefer vectors. An audio embedding is a vector representation whose distances reflect its chosen features or training objective. Monochord's is simple: the energy in twenty-four bands and how it varies, twelve chroma bins and the flux, sixty-two numbers. Learnt embeddings are often taken from an intermediate or output layer, trained on millions of tracks to predict tags or what people play together. Nearest neighbours in the embedding give more like this. The risk is that near in the embedding means near in recording conditions, not in music.

Here are all sounds of this series so far, each placed by its embedding alone, flattened onto the two directions along which the embeddings vary most. Colour them by act. The acts overlap almost completely. The first two lean a little toward the top, with their pure tones and single strings, but every act has its plain tones and its full textures, and they land wherever they sound like they belong. The map knows sound, not subject: these features emphasize some similarities and miss others. A two-dimensional PCA projection also discards variation, so this picture is not a validated map of perceived similarity.

Your turn. A Variation, then three other clips. Two are its nearest neighbours by the embedding, from other parts; one is the farthest clip in the whole series. Which is the odd one out?

The second: Part 48's test tones, the farthest clip in the series from this Variation. The neighbours were Part 21's harmonized Tune and Variation 13: the same melody, similar instruments, found by sixty-two numbers that know nothing of melody. Near and far, here, agree with the ear.

Which brings a cautionary tale. In 2002 George Tzanetakis and Perry Cook published a genre dataset: a thousand thirty-second excerpts in ten genres. For a decade it was the field's benchmark, with hundreds of papers reporting accuracies on it. In 2013 Bob Sturm looked inside: repeated excerpts, mislabelled ones, distorted ones, and many from the same few artists. With an artist in both training and test sets, a system can learn the artist, or the recording, and seem to have learnt the genre. Benchmarks are data too: look at them.

6Right for the wrong reasonsFoundations3 min

How do you know what a classifier really learnt?

A horse explains the danger. In Berlin in 1904 a horse called Clever Hans appeared to do arithmetic, tapping out the answers with a hoof. The psychologist Oskar Pfungst found the truth: the horse read tiny changes in the questioner's posture, and stopped tapping when they relaxed. In 2014 Bob Sturm proposed calling a music classifier a horse if it gets right answers from cues that have nothing to do with the music. And the test: change what should not matter, and see whether the answers change.

Your turn, and you will need headphones or loudspeakers with real bass. Five seconds of a Variation, twice. Is there any difference, and if so, in which?

The second carries a faint mains hum, at fifty hertz and its harmonics, twenty-four decibels down, as if recorded in another studio. Easy to miss. A classifier did not miss it.

The task: from four-second training excerpts, did this Variation come from the first thirty parts or the last thirty? Every recording from the later parts carries that faint hum. A classifier on Monochord's embedding scores percent. Impressive. Remove the hum, change nothing about the music, and the same classifier falls to percent. It had learnt the hum. Trained honestly, without any hum, and tested on clips it never saw, it scores percent, no better than always guessing the commoner half, . This classifier and this split do not establish that the music contains no information about its half of the series. The counterfactual drop shows that the added hum strongly affected this fitted classifier.

Could we have caught it without removing the hum? Look at what the model uses. Here is how the size of its weights divides among the embedding's four kinds of number, for the classifier trained with the hum and for the one trained without. The blocks look alike. But zoom in on the three lowest bands, where fifty, a hundred and a hundred and fifty hertz fall: they carry per cent of the hum classifier's weight, against for the other: three bands out of sixty-two, doing a large share of the work. A sign to go and listen to the bass.

How do you catch a horse? Split the data by artist, album and studio, not by excerpt, so that no recording sits on both sides. Intervene: filter, add noise, change the level, re-encode, everything that should not matter. Look at what the model uses: its weights, its saliency, its errors; feature weights depend on scaling and correlated predictors; feature weights depend on scaling and correlated predictors. Test on music made elsewhere: another studio, decade or culture. A high score is a hypothesis about what was learnt, not a proof.

7Learning from listeningPractice3 min

Can what other people play tell you what you will like?

The other way to find music ignores the sound altogether. Collaborative filtering: people who played what you played also played this. It uses no audio, only who played what, and how often. From 2006 to 2009 the Netflix Prize offered a million dollars for ten percent better predictions of film ratings, and made these methods famous. Music services have plays, not ratings: implicit feedback, in which not playing a song is not the same as disliking it. In 2015 Spotify's Discover Weekly began giving every listener thirty songs a week, largely from these methods.

Here is what a recommender actually has. A matrix: one row per listener, one column per clip, bright where a listener played a clip, sorted by how much each plays and is played. Only per cent of its cells are lit: most listeners never meet most music. Factorize it, eight numbers for each listener and each clip, and the product fills in every cell, including the dark ones. Those filled-in guesses are the recommendations.

The standard method for plays is from Yifan Hu, Yehuda Koren and Chris Volinsky, in 2008. Whether a listener played a song is the preference; how often sets the confidence in it. Find a short vector for every listener and every song so that their dot product predicts the preference, weighted by the confidence. The listener's vector is a fitted profile of observed behaviour, the song's its profile, both learnt from the plays alone. Solve by alternating least squares: fix the songs and solve for every listener, then fix the listeners and solve for every song.

Monochord simulates listeners whose tastes it knows, songs from the series' library, and their plays; a fifth of each listener's songs are hidden, and each method must find them. Random songs find percent in the top ten. Recommending the most played songs to everyone finds percent: popularity is a strong baseline. The factorization finds percent, by fitting the simulated play patterns.

Here are the three songs it suggests to its most active listener, none of which that listener had played.

8Cold start and exploringFoundations2 min

How does a song nobody has played ever get recommended?

Plays have a weakness. Tens of thousands of new tracks reach the services every day. Collaborative filtering knows nothing about a song until people play it, and people mostly play what is recommended, so a new song can wait for ever. A new listener has the same problem: no plays, no taste. Two fixes: use the sound, and spend some recommendations on finding out.

Monochord tries the first fix. It hides every play of songs, so that to the factorization they are new. On the songs people did play, it learns a map from the sound's embedding to the profile the factorization found. Then it applies the map to the new songs and recommends them by their sound alone. It finds percent of listeners' new songs in their top five, against at random: in our simulation, taste follows the sound partly, and the map recovers that part.

Hear one of the new songs, and the played song whose sound is nearest to it in the embedding: a content neighbour; this similarity alone does not determine a real recommendation.

The second fix is to explore. Show some listeners a song the system is unsure about, and learn from what they do. This is a bandit problem: trade off exploiting what works against exploring what might. Thompson sampling recommends each song with the probability that it is the best, given everything seen so far. The cost is real: an exploration is a recommendation that may be worse. But without it, the system never learns about what it never shows, which the next chapter measures.

9Popularity feeding on itselfPractice2 min

What happens when a recommender learns from its own recommendations?

Recommenders change what they measure. Monochord runs a simple loop. A service recommends each listener the five most played songs. Listeners play a recommendation if it suits them, their true taste deciding. Those plays feed the next round's ranking. Beside it runs a world without a recommender, where listeners browse at random and play what suits them. It is Part 60's MusicLab, with the social influence built by engineers.

Here is the inequality of plays, round by round. Without a recommender, listeners spread their plays: the Gini stays low. With the loop, the first few songs to be played are recommended to everyone, played more, and recommended more: the Gini climbs toward one. Exploring thirty per cent of the time slows the runaway, because songs outside the top get a chance to be played. At the end, the top one percent of songs hold percent of all plays with the loop, against without a recommender.

Another view of the same thirty rounds: a Lorenz curve, the clips lined up from least to most played, and the share of plays they hold together. Equal shares would be the diagonal. On their own, listeners give the most-played tenth of the clips per cent of plays. With the recommender exploring, per cent. With popularity alone, per cent: nearly everything, and the curve hugs the floor until the very last clips.

What does it mean? A recommender trained on its own outputs measures its own influence and calls it taste. Real services mix popularity, personal taste, exploration and human editors, and study the loop carefully. Offline tests on logged plays inherit the loop, because the logs reflect exposure, selection and other routes to discovery. Possible remedies include randomized exploration and inverse-propensity weighting, when exposure probabilities and overlap are known well enough. What people play is partly what they were shown.

10Playlists, fairness and metadataFoundations3 min

What makes a good sequence, and who gets heard?

Your turn. Six Variations, a few seconds each, twice: once in a random order, once ordered so that each sounds like the one before. Which was ordered?

The second: neighbouring snippets share instruments and textures, while the first jumps about. Smoothness is one thing a playlist can be asked for.

How was it ordered? A smooth playlist is a short path through the songs, step by step in the embedding. That is a travelling-salesman-like shortest open-path problem: start with the nearest neighbour each time, then swap pairs of steps while the path gets shorter. Ordering every Variation this way makes a path about half as long as a random order. But listeners also want variety, a shape, a beginning and an end: smoothness is not the only virtue of a playlist.

Here is what the builder did, on the map of sounds from Chapter 5. Each dot is a Variation. A random order zig-zags across the map: every step a jump in sound. The builder's order walks: from each Variation to its nearest unvisited neighbour, then untangled where two steps cross. Its path is long against , which is what you heard as smoothness. A smooth path is not the only good playlist: contrast, surprise and a shape over the hour matter too, and nearest neighbours know nothing of them.

Who gets heard is a question of fairness. To listeners: do recommendations serve niche tastes as well as mainstream ones? To artists: exposure follows popularity, and popularity follows exposure, as Chapter 9 showed. Studies have found recommenders amplifying imbalances already present in the plays, for instance by artists' gender. The remedies: constraints on exposure, re-ranking, and measuring who is shown, not only who is played.

And finding depends on naming. Every finder needs to know what it has found: titles, artists, writers, dates. Recordings carry ISRC codes and compositions ISWC codes, and linking the two is still often done by hand. MusicBrainz, begun in 2000, is an open, crowd-edited encyclopedia of both. And Part 60's unmatched royalties are a metadata problem: a fingerprint without a name pays nobody.

11Frontier: foundation models and creatorsResearch3 min

What changes when one model listens to everything?

Two frontiers. The first is scale. Music foundation models are networks trained on huge unlabelled collections and then adapted to many tasks; check the latest, which change every year. Some put audio and text in one space, so music can be searched by a sentence: a sad waltz on an out-of-tune piano. One embedding then serves tagging, similarity, recommendation and generation. And what they learn from is whatever was collected: Chapter 6's lesson, at a scale nobody can inspect by hand.

The second is the effect on the people who make the music. Recommendation shapes what is made: musicians tune songs to the first seconds, to playlists, to short videos. Measuring that needs data across years of releases and plays, which services rarely share. Regulators now ask: the European Union's Digital Services Act of 2022 requires large platforms to explain their recommenders. And the effect of a recommender is a causal question: what would have been made, and heard, without it?

What evidence is there? Some services count eligible streams after about thirty seconds, subject to platform rules and agreements; that does not guarantee a fixed payment. Hubert Léveillé Gauvin measured the top-ten hits in the United States: their instrumental introductions shrank from about twenty seconds in the mid-1980s to about five by the mid-2010s. The voice and the title arrive sooner, and songs grew shorter in the streaming years. But radio, music video, changing taste and attention all overlap those years; a trend is not a cause. The principle is older than streaming: what a system rewards, people make more of. Chapter 9's loop, with musicians inside it.

A research problem to end on. Simulate a market of listeners with tastes, artists who adapt to what is rewarded, and a recommender in the middle. Fit it to what can be observed: release patterns, song lengths, the concentration of plays over time. Then compare worlds: ranking by popularity, by personal taste, with exploration, and with no recommender at all. The question: how much of the change in music over the streaming era did recommenders cause? An answer would inform both how platforms are built and the regulation now being written.

Variation 63, recap and problemsAll tracks2 min

Every part ends by doing something to the Tune with what it built. Here are five noisy seconds from each of three earlier Variations, chosen at random, in a bar where the music is only three decibels above the noise. After each, the fingerprinter's answer appears.

Row sixty-three of the ledger: . The ledger is now also a library, and these three chosen excerpts were found under the demonstrated noise conditions.

What did we find? Fingerprints pair spectrogram peaks into hashes, and true matches agree in time. They survive noise and codecs, and identify recordings, not songs. Chance matches scatter, but correlated music and multiple comparisons require empirical threshold calibration. Embeddings describe sound, and a classifier can learn a hum instead of the music. Implicit matrix factorization fits profiles from plays, and the sound rescues songs nobody has played. And popularity feeds on itself, while exploring and fairness push back.

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 source separation, asking which instruments a mix contains. In machines that compose, testing for memorization by matching. In generative audio, detecting generated tracks. In research, with benchmarks, horses and honest evaluation. And in the concert, the Variations in one playlist.

And in practice. Identify recordings with fingerprints and songs with chroma matching. Evaluate with splits by artist and studio, and test what should not matter. Beat the popularity baseline before claiming a recommender works, and explore. And name everything: codes on every file, linked.

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

Where it goes next. Separated stems searched and remixed in Part 64; machines that compose trained on what services collect in Part 65; generated audio, watermarks and fingerprints in Part 66; evaluation, leakage and listening tests in Part 67; the concert's programme ordered in Part 68.

Key results

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

Hash\(\displaystyle h = (f_1, f_2, \Delta t) \mapsto 24\ \text{bits}\)
Votes\(\displaystyle \text{offset} = t_{\text{clip}} - t_{\text{query}}\)
Chance\(\displaystyle \lambda = \frac{n_q\, n_{db}\, 2^{-24}}{\text{tracks} \times \text{offsets}},\ \ P(\ge m) \le N\,\frac{\lambda^m}{m!}e^{-\lambda}(1 + \dots)\)
Implicit ALS\(\displaystyle x_u = (Y^\top C_u Y + \lambda I)^{-1} Y^\top C_u\, p_u\)
Gini\(\displaystyle G = \frac{\sum_i \sum_j |x_i - x_j|}{2 n^2 \bar x}\)

Try it

Lab 63 · Finding music, computed

Fingerprint a library of pieces and name noisy five-second excerpts with their offsets, check how rarely chance produces a false match, learn listeners' tastes from their plays, and watch popularity feed on itself.

Figure produced by Lab 63: Finding music, computed
Produced by the lab below, seed 0, in 1.5 s.
python -m videos.music.labs 63 needs numpy, scipy, matplotlib · download lab63.py · source on GitHub
library: pieces, hashes                                                        12, 8,082
five-second queries at +20 dB: named                                           12 of 12
five-second queries at +5 dB: named                                            11 of 12
five-second queries at +0 dB: named                                            12 of 12
five-second queries at -5 dB: named                                            12 of 12
chance hits for a query, in all; at least 6 in one place                       0.193, p = 2.8e-26
recall at 10: popularity, implicit ALS                                         0.137, 0.198
feedback loop (explore 0.2): Gini, top 1% share; without a recommender         0.77, 0.19; 0.16, 0.02
ear problem: the same piece at each noise level; was it named? (listen first)  +20 dB: named, +5 dB: named, +0 dB: named, -5 dB: named

Fingerprints keep only spectrogram peaks, paired into hashes whose votes must agree in time; chance rarely piles them up; plays alone reveal tastes; and a recommender that learns from its own recommendations concentrates attention unless it explores.
The code (93 lines; it asserts its own result)
"""Lab 63: finding music, computed: a fingerprinter over a small library of rendered pieces, queried through noise;
the false-match arithmetic; implicit matrix factorization on simulated listeners against a popularity baseline; and
the feedback loop of a recommender that recommends what is already played."""

import numpy as np

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

TITLE = "Finding music, computed"
GOAL = ("Fingerprint a library of pieces and name noisy five-second excerpts with their offsets, check how rarely chance "
        "produces a false match, learn listeners' tastes from their plays, and watch popularity feed on itself.")
TASKS = [
    "Change SNRS. At what noise level does the fingerprinter start to fail on this library?",
    "Change ALPHA, the confidence given to repeated plays. Does recall at 10 rise or fall?",
    "Change EXPLORE. How much exploration does it take to keep the top 1% of songs under a third of all plays?",
]
SNRS = [20, 5, 0, -5]
ALPHA = 20.0
EXPLORE = 0.2


def piece(seed, seconds=12.0):
    rng = np.random.default_rng(seed)
    y = np.zeros(int(seconds * SR))
    t = 0.0
    while t < seconds - 0.5:
        d = float(rng.choice([0.25, 0.5]))
        z = organ_tone(110 * 2 ** (int(rng.integers(0, 48)) / 12), d, partials=3 + seed % 5, rolloff=0.6 + 0.07 * (seed % 4))
        k = int(t * SR)
        y[k:k + len(z)] += z[: len(y) - k]
        t += d
    return y / np.max(np.abs(y)) * 0.8


def run(seed=0):
    rng = np.random.default_rng(seed)
    lab = labs.Lab()
    idx = F.Index()
    songs = [piece(s) for s in range(12)]
    for k, y in enumerate(songs):
        idx.add(f"piece {k}", y, SR)
    lab.row("library: pieces, hashes", f"{len(songs)}, {idx.size:,}")
    clips, answers = [], []
    for snr in SNRS:
        ok = 0
        for k in range(len(songs)):
            a = float(rng.uniform(0, 6))
            q = songs[k][int(a * SR):int((a + 5) * SR)]
            q = q + rng.standard_normal(len(q)) * np.std(q) * 10 ** (-snr / 20)
            r = idx.query(q, SR)
            ok += r[0]["track"] == f"piece {k}"
            if k == 0:
                clips.append(Clip(q / np.max(np.abs(q)) * 0.8, SR))
                answers.append("named" if r[0]["track"] == "piece 0" else "missed")
        lab.row(f"five-second queries at {snr:+d} dB: named", f"{ok} of {len(songs)}")
        if snr == SNRS[0]:
            assert ok >= len(songs) - 1
    fm = F.false_match_rate(bits=24, query_hashes=400, db_hashes=idx.size, tracks=len(songs), offsets=400)
    lab.row("chance hits for a query, in all; at least 6 in one place", f"{fm['chance_hits']:.3f}, p = {fm['p_some_bin_at_least'][6]:.1e}")
    L = F.listeners(n_users=300, n_items=150, seed=seed, popularity=0.3)
    train, held = F.split(L["R"], 0.2, seed=1)
    fit = F.implicit_als(train, k=8, alpha=ALPHA, iters=8)
    S = fit["X"] @ fit["Y"].T
    pop = np.tile(train.sum(axis=0), (train.shape[0], 1)).astype(float)
    r_als, r_pop = F.recall_at_k(S, held, train), F.recall_at_k(pop, held, train)
    lab.row("recall at 10: popularity, implicit ALS", f"{r_pop:.3f}, {r_als:.3f}")
    assert r_als > r_pop
    loop = F.feedback_loop(n_users=200, n_items=100, rounds=15, seed=seed, explore=EXPLORE)
    lab.row(f"feedback loop (explore {EXPLORE}): Gini, top 1% share; without a recommender",
            f"{loop['gini'][-1]:.2f}, {loop['top1']:.2f}; {loop['gini_own'][-1]:.2f}, {loop['top1_own']:.2f}")
    lab.audio = concat(clips, gap=0.6)
    lab.row("ear problem: the same piece at each noise level; was it named? (listen first)", ", ".join(f"{s:+d} dB: {a}" for s, a in zip(SNRS, answers)))
    fig, (ax1, ax2) = labs.figure(2)
    S0 = F.spectrogram(F.to_8k(songs[0][: 5 * SR], SR))
    pts = F.peaks(S0)
    ax1.imshow(S0[:256], origin="lower", aspect="auto", cmap="magma")
    ax1.plot(pts[:, 0], pts[:, 1], ".", color="white", ms=3)
    ax1.set_ylim(0, 256)
    ax1.set_xlabel("frame")
    ax1.set_ylabel("bin")
    ax2.plot(loop["gini"], color=labs.GOLD, label="recommender")
    ax2.plot(loop["gini_own"], color="0.6", label="none")
    ax2.set_xlabel("round")
    ax2.set_ylabel("Gini of plays")
    ax2.legend(fontsize=7)
    lab.fig = fig
    lab.note = ("Fingerprints keep only spectrogram peaks, paired into hashes whose votes must agree in time; chance rarely "
                "piles them up; plays alone reveal tastes; and a recommender that learns from its own recommendations "
                "concentrates attention unless it explores.")
    return lab

Now change it

  1. Change SNRS. At what noise level does the fingerprinter start to fail on this library?
  2. Change ALPHA, the confidence given to repeated plays. Does recall at 10 rise or fall?
  3. Change EXPLORE. How much exploration does it take to keep the top 1% of songs under a third of all plays?

Problems, with solutions

Try each problem before opening its solution.

  1. Compute. A query has 300 hashes; the library 50 million; hashes are 24 bits. How many chance hits? Spread over a million clip-offsets, how many per bin?

    Solution

    Each query hash equals a given stored hash with probability 2⁻²⁴ ≈ 6.0 × 10⁻⁸, so the expected chance hits are 300 × 5 × 10⁷ × 2⁻²⁴ ≈ 894. Spread over 10⁶ bins that is about 0.0009 per bin; the chance that some bin collects five is, by the Poisson tail and a union bound, about 10⁶ × 0.0009⁵ / 120 ≈ 5 × 10⁻¹². A true match's dozens of aligned votes stand far above chance.

  2. Prove. Show that with confidences c_ui fixed, each ALS step solves a weighted least-squares problem exactly, so the loss never increases.

    Solution

    The loss Σ c_ui (p_ui − x_uᵀ y_i)² + λ(Σ‖x_u‖² + Σ‖y_i‖²) is, for fixed Y, a sum over users of independent quadratics in each x_u, with minimizer x_u = (YᵀC_uY + λI)⁻¹ YᵀC_u p_u; the matrix is positive definite, so this is the unique minimum. Replacing X by it cannot raise the loss; the same holds for Y given X. Alternating, the loss is non-increasing and bounded below, so it converges (to a stationary point, not necessarily the global minimum).

  3. Ear. The lab plays queries at several noise levels; guess where the fingerprinter fails, then check.

    Solution

    The lab prints which were named. Compare with the level at which you stopped hearing the piece: the ear follows a tune through noise by its continuity, while the fingerprinter needs enough of its exact peaks to survive.

  4. Build. Add exploration by Thompson sampling to the feedback loop, and measure inequality and recall.

    Where to look. Keep a Beta posterior on each song's chance of being played when shown; each round, draw from every posterior and show each listener the five highest draws; update with the plays. Report the Gini of plays and the recall against the listeners' true tastes, against plain popularity and against random exploration at the same rate.

  5. ★ How much of the change in music over the streaming era did recommenders cause?

    Where the frontier is. Simulate listeners, artists who adapt to what is rewarded and a recommender between them; fit the simulation to what can be observed (release patterns, song lengths, introductions, concentration of plays over time); compare worlds with popularity ranking, personal ranking, exploration and no recommender. Natural experiments (changes in a platform's ranking, by country and date) would sharpen it.

Notes and sources

Sources

  • M. Müller, Fundamentals of Music Processing (2nd ed., 2021); O. Celma, Music Recommendation and Discovery (2010); M. Schedl et al., "Current challenges and visions in music recommender systems research", IJMIR (2018).
  • A. Wang, "An industrial-strength audio search algorithm" (ISMIR, 2003); J. Haitsma and T. Kalker, "A highly robust audio fingerprinting system" (ISMIR, 2002); A. Ghias et al., "Query by humming" (ACM Multimedia, 1995).
  • G. Tzanetakis and P. Cook, "Musical genre classification of audio signals", IEEE Trans. Speech and Audio Processing (2002); B. L. Sturm, "The GTZAN dataset: its contents, its faults, their effects on evaluation, and its future use" (2013); B. L. Sturm, "A simple method to determine if a music information retrieval system is a horse", IEEE Trans. Multimedia (2014).
  • Y. Hu, Y. Koren and C. Volinsky, "Collaborative filtering for implicit feedback datasets" (ICDM, 2008); M. J. Salganik, P. S. Dodds and D. J. Watts, "Experimental study of inequality and unpredictability in an artificial cultural market", Science (2006); O. Celma and P. Cano, "From hits to niches?" (2008).
  • H. Léveillé Gauvin, "Drawing listener attention in popular music: testing five musical features arising from the theory of attention economy", Musicae Scientiae (2018).

Review qualifications: cached-library counts and fixed numerical examples describe a computation snapshot. Recognition rates are finite synthetic trials, not guarantees at commercial scale. Hash false-match arithmetic assumes uniform independent hashes and is not an operational false-positive certificate. Classifier standardization is fitted on each training split only; exact-run and embedding distances have limited scope.

  • P. Knees and M. Schedl, Music Similarity and Retrieval: An Introduction to Audio- and Web-based Strategies (2016).
About this partfrom its README

Part 63 of a sixty-eight-part course in music (see the series plan and the syllabus), the third part of Act XI, Listening Machines. Five seconds in a noisy bar are enough for a phone to name a song among a hundred million; a service with millions of listeners chooses what each of them hears next. This part builds both kinds of finder: Wang's constellation fingerprint with its hash table and votes, tested through noise, codecs, speed changes and samples, and a melody search that finds the song rather than the recording; then content embeddings, a classifier that was right for the wrong reason, implicit matrix factorization on simulated listeners, the cold start, a recommender feeding on its own popularity, and playlists. The tools are Monochord's (explainer/music/monochord/mir/finder.py); the library searched contains the locally available cached sounds of Parts 1 to 60 (908 clips, 3.7 hours, 1.15 million hashes), and the listeners are simulated with tastes known, so every answer can be checked.

  • A song from a noisy bar. Five seconds of Variation 40, the music no louder than the bar, named with its offset (23 votes against the runner-up's 12); how the search began (Shazam, 2002); the plan.
  • 1. A constellation of peaks. Why not compare waveforms; a Variation's spectrogram reduced to its peaks (about 20 a second); the peaks alone, heard.
  • 2. Hashes and votes. Pairs of peaks as 24-bit hashes; the table; voting for a clip and an offset; what a match looks like (44 of the true clip's 179 shared hashes on one diagonal, the Tune's repeats on shorter ones; the runner-up's 32 scattered).
  • 3. Noise, codecs and chance. One query in three bars, heard (named at +10 and 0 dB, lost at −5); recognition against white noise and bar noise (bar noise is harder: 61 % at 0 dB, 25 % at −5); how long a query must be (at 0 dB, 9 % at one second, 65 % at five, 81 % at eight), one second and eight heard; an ear question on a 16 kbit/s codec (the first was coded; 75 % still named); the arithmetic of chance (27 chance hits per query, scattered); a hundred million tracks (six chance hits in one place stays below one in 10¹⁶).
  • 4. Recordings, not songs. The Tune rendered afresh (its best guess 38 votes, a tenth of a true excerpt's); an ear question on a Variation played 4 % fast (not named: at 1 % fast 59 %, at 2 % 25 %); a Variation as a sample under another (found 93 % level, 47 % at −12 dB; the demo at −12 is missed); a hummed query, slower, in another key and a little out of tune, missed by the fingerprint and found first of 30 melodies by a pitch contour and time warping.
  • 5. Tags and embeddings. Tags and who writes them; Monochord's 62-number embedding; all 908 clips on its first two principal components (the acts overlap almost completely: it knows sound, not subject); an ear question on neighbours (the second, Part 48's test tones, is the farthest clip in the series); GTZAN's faults.
  • 6. Right for the wrong reasons. Clever Hans; an ear question (a Variation with a faint mains hum: the second); a classifier of first-half against second-half Variations scores 81 % with the hum, 43 % with it removed, and 50 % trained honestly and split by clip, no better than guessing the commoner half (56 %); its weight on the three lowest bands (9 % against 3 %); how to catch a horse.
  • 7. Learning from listening. Collaborative filtering; the play matrix (500 listeners by 300 clips, 11 % of cells lit) and its factorization; implicit ALS (Hu, Koren and Volinsky, 2008); recall at 10 (random 0.038, popularity 0.077, ALS 0.127); one listener's top three, heard.
  • 8. Cold start and exploring. Thirty clips nobody has played, scored from content (recall at 5: 0.28 against 0.17 at random); a cold clip and its nearest played neighbour, heard; exploring.
  • 9. Popularity feeding on itself. A recommender that shows the most played; the Gini of plays over thirty rounds (0.97; 0.71 exploring 30 %; 0.13 with no recommender); Lorenz curves (the top tenth of clips gets 99 %, 73 % and 14 % of plays); what it means.
  • 10. Playlists, fairness and metadata. An ear question (random order or smooth? the second was ordered); nearest neighbour and 2-opt (path 226 against 439); the path on the map; who gets heard; credits and metadata.
  • 11. Frontier: foundation models and creators. Music foundation models and text-to-audio search; effects on creators; the evidence so far (Léveillé Gauvin, 2018: introductions from about 20 seconds to about 5); ★ research problem: how much of the change in music over the streaming era did recommenders cause?
  • Variation 63, recap and problems. Five noisy seconds of three earlier Variations (27, 34 and 56), each named; the ledger; what we found; five problems; where it comes back; in practice; references; Part 64.
What is computed and built

python -m videos.music.music63.compute (several minutes: every clip of Parts 1 to 60 is read and indexed) fills .cache/music63/.

Item What it computes Checked against
library, hook, constellation, matches the index; a noisy query named with its offset; peaks and hashes; shared hashes the excerpt's true clip and offset (tests)
robust, length, lengthpair, speed, sampled recognition through noise, codecs, short queries, speed changes and samples the true clips, with duplicate audio counted as aliases (tests)
falsematch, scale chance agreement, by the Poisson tail; pure-noise queries; a fresh recording votes for pure noise against true excerpts (tests)
hum a sung query's YIN contour against thirty melodies by time warping the melody sung (tests)
horse, map, neighbours the hum classifier, split by clip; the embedding's principal components; nearest and farthest the hum and the clips' parts (tests)
recs, matrix, loop, lorenz, playlist ALS against popularity; the cold start; the feedback loop; playlists the simulated tastes (tests)

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

Sounds. Every clip of Parts 1 to 60, as each part stored it; simulated bar noise (voices and glasses); Part 58's coder; Part 38's piano; Part 8's alto voice for the hummed query.

What the models are, and are not. The fingerprint follows Wang (2003): 8 kHz, 1024-point frames, peaks in 15 × 11 neighbourhoods, five partners per anchor, 24-bit hashes; real services tune all of these and add verification. Some parts reuse a Variation's audio in another clip; such duplicates are counted as correct. The embedding is 62 hand-made numbers; learnt embeddings are far richer, and the map's overlap is a property of this one. The listeners are simulated: tastes on six factors, partly predictable from content, plays drawn from them; real data have none of this tidiness. The melody search compares against thirty melodies by full time warping; real services index millions.

Companion material in this repository

The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
  1. Hook: five seconds of a Variation in a noisy bar, named with its offset; how the search began; the plan.
  2. A constellation of peaks: why not waveforms; a Variation's peaks; the peaks alone, heard.
  3. Hashes and votes: pairs of peaks as hashes; the table; voting for a clip and an offset; what a match looks like.
  4. Noise, codecs and chance: one query in three bars, heard; noise curves; how long a query must be, heard; a codec ear question; chance; a hundred million tracks.
  5. Recordings, not songs: a fresh recording of the Tune; an ear question on a query played 4 % fast; samples under other tracks, heard; a hummed query found by its melody.
  6. Tags and embeddings: tags; Monochord's embedding; the series on its principal components; an ear question on neighbours; GTZAN's faults.
  7. Right for the wrong reasons: Clever Hans; an ear question (the hum); the horse's scores; where its weight goes; how to catch a horse.
  8. Learning from listening: collaborative filtering; the play matrix and its factors; implicit ALS; recall at 10; one listener's recommendations, heard.
  9. Cold start and exploring: unplayed clips scored from content; a cold clip and its neighbour, heard; exploring.
  10. Popularity feeding on itself: the feedback loop; inequality over rounds; Lorenz curves; what it means.
  11. Playlists, fairness and metadata: an ear question (random or ordered?); nearest neighbour and 2-opt; the path on the map; who gets heard; metadata.
  12. Frontier: foundation models; effects on creators; the evidence so far; the research problem.
  13. Variation 63: three earlier Variations, five noisy seconds each, named. Outro: problems, payoffs.

Covers: fingerprinting and its false-match arithmetic; robustness to noise, codecs, length, speed and samples; query by humming; tagging and embeddings; the benchmark that turned out to be flawed, and classifiers that were right for the wrong reasons; collaborative filtering and implicit feedback; cold start; exploration; popularity feedback; fairness; metadata. Built and computed: monochord/mir/finder.py: a fingerprinter over every sound of Parts 1 to 60 (908 clips, 1.15 million hashes): bar noise at 0 dB 61 % named, 8 s queries 81 %, 2 % fast 25 %, a sample 12 dB down 47 %; the Poisson false-match tail (six chance hits in one place below 10⁻¹⁶ at a hundred million tracks); a hummed query found first of 30 melodies by its contour; a hum classifier at 83 % that falls to chance; implicit ALS on simulated listeners (recall at 10: 0.127 against 0.077 for popularity); content for the cold start (0.28 against 0.17); a feedback loop (Gini 0.97, 0.71 exploring, 0.13 without); playlists by nearest neighbour and 2-opt. Variation 63: three earlier Variations, five noisy seconds each, named (3 of 3). Frontier: music foundation models (verify); creator-side effects of recommendation. Reading: Wang (2003); Hu, Koren & Volinsky (2008); Sturm (2013, 2014); Salganik, Dodds & Watts (2006).

Build the film

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

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

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