Machines that Compose
How do machines learn to compose from music, and how much of what they write is copied?
An ear question: three pairs of harmonized chorale phrases, one Bach's (BWV 166.6, unseen by the machines) and two by machines; Hofstadter's 1997 concert, where an audience took Cope's EMI for Bach. Composing machines from the dice minuet to the Music Transformer; rules, chance and statistics. The corpus: 163 of Bach's major chorale tunes transposed to C, only 114 different hymn tunes, so split by tune. Markov chains of orders 0 to 8: bits per note on unseen tunes (3.40 at order 2, the best; 3.83 at order 8); surprise at phrase boundaries; orders heard. Copying: order 8 copies runs of 26 notes and 91 per cent of what it writes, against 11 per cent for Bach's own tunes; a 40-note copy heard beside its source; the trade between prediction and copying. Constraints sampled exactly by backward messages (0.66 per cent of free draws end legally). Cope's recombinancy: four chorales in one tune, 79 per cent copied. Tokens three ways. A pocket transformer on the tunes alone and in twelve keys, stopped where the tunes set aside say (3.76 and 3.49 bits); trained too long it recites 40 notes of BWV 322. Temperature: an ear question; intervals closest to Bach at 1.0, notes outside the key rising from 6 to 19 per cent. DeepBach; a machine's chorale harmonized by Part 17 with no parallels; Bach's harmony beside Part 17's. An ear question on copying; every machine before the same judges, where only copying separates them; pitfalls and listening tests. Frontier: form, control and attribution. Variation 65: the Tune's first phrase continued at five temperatures, uncurated.
What you need. Part 14 for the next-note model; Part 17 for chorales, chord models and voice leading; Part 42 for composing as search; Part 61 for networks; Part 63 for evaluation and leakage. Markov chains, perplexity, dynamic programming, attention and next-token training, data augmentation, early stopping.
- Ideas, mathematics and history
- Markov chains and plagiarism, constraints, Cope, recurrent networks, the Music Transformer, tokenizations, evaluation
- What we build, compute and hear
- Markov models and a small transformer; the Tune continued, with the copying measured
What you will be able to do
Foundations
- Hear Markov tunes of several orders, a copied stretch beside its source, and constrained and recombined tunes.
- Hear a transformer's tunes, the same opening at three temperatures, and a machine's chorale beside Bach's.
- Explain why a model that copies less coheres less, and why copying must be measured rather than heard.
Full course
- Fit variable-order Markov chains, score bits per note on unseen music, and measure copying by exact runs.
- Sample a chain exactly under constraints with backward messages; recombine phrases where they connect.
- Train a small transformer on tokens with augmentation and early stopping; sample with temperature.
Research
- Map the frontier of novelty against quality for generators of many sizes, with blind listening tests.
Practice
- Split by work, report uncurated output, likelihood and copying together, and know whose music trained a model.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Foundations 24 min · Full course 29 min · Research 31 min · Practice 29 min.
- 0Bach, a professor and a programFoundations2 min
- 1Dice, rules and chanceFoundations2 min
- 2Counting what comes nextFoundations3 min
- 3Novelty and copyingFoundations2 min
- 4ConstraintsFoundations2 min
- 5RecombinationFoundations2 min
- 6Music as tokensPractice2 min
- 7A transformerFoundations3 min
- 8TemperatureFoundations2 min
- 9Four partsFoundations3 min
- 10Judging machinesPractice3 min
- 11Frontier: form, control and attributionResearch2 min
- Variation 65, 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.
Bach, a professor and a programFoundations2 min
In 1997 an audience in Oregon heard three pieces, one of them by Bach. Your turn. Three pairs of phrases in the style of a Bach chorale, on an organ. One is Bach's own. Two were written by machines, and harmonized by another. Which is Bach's?
The second was Bach's, the chorale , which the melody generators did not see while learning; the separate Part 17 harmonizer uses a broader chorale corpus. The first tune came from a chain that counts which note follows which; the third from a small transformer, the kind of network behind today's language models: for each, the first draw that stayed in the key and could be harmonized, by Part 17's search. If you hesitated, you are in good company.
The question is older than these machines. In 1997, at the University of Oregon in Eugene, the cognitive scientist Douglas Hofstadter put three pieces before an audience. One was by Bach. One was by Steve Larson, who taught music theory there, written in Bach's style. One was by EMI, a program David Cope had been building since 1981. As it was reported, the audience took the program's piece for Bach's, and the professor's for the computer's. Hofstadter had expected the program to be found out at once, and was troubled. This part asks what such a program knows, and how much of its music is simply its training's music, copied.
Here is the plan. Dice, rules and chance, the composing machines that came before learning. Counting which note follows which, on the melodies of Bach's chorales. An empirical trade in these models between copying and prediction; coherence is not measured directly. Constraints, and Cope's recombination. Music as tokens, a transformer, and temperature. And four-part harmony, how to judge a composing machine, and who owns what it copies.
1Dice, rules and chanceFoundations2 min
What did composing machines do before they could learn?
Composing machines are older than computers. In 1792 a game appeared, attributed to Mozart, that built a minuet from bars chosen by dice; Part 42 played one of ours. In 1957 Lejaren Hiller and Leonard Isaacson's Illiac Suite drew notes at random and tested each against rules of counterpoint, drawing again when one failed. Iannis Xenakis wrote laws of chance for whole clouds of notes. In 1981 David Cope began EMI. And then learning: DeepBach, a network that harmonizes chorales, in 2016, and the Music Transformer in 2018.
Three kinds of machine, then. Some follow rules written by hand: the composer's knowledge made explicit, and the machine only searches, as in Part 42. Some shape chance with a distribution: dice, urns, Xenakis's clouds. And some learn statistics from music, what follows what, counted or fitted. This part is about the third kind. It learns from a corpus, so it can only be as new as its model allows, and limited by its data, architecture and objective.
The music to learn from: Bach's chorales, the hymns he harmonized for four voices. Here are the first two phrases of one held out from the melody generators.
Part 17's table holds chorales. The in major keys and common time, transposed to C, give the corpus: their soprano lines, the hymn tunes. But there are only different tunes among them, because Bach set many tunes more than once. A test tune harmonized differently in the training set would be a test already seen. So the split is by tune: chorales to learn from, tunes kept back, never seen in any harmonization.
2Counting what comes nextFoundations3 min
How far back should a machine remember?
The simplest learner counts. Treat each note as one symbol: its pitch, its length, and whether a phrase ends on it. The chance of the next note, given the last few, is estimated by how often that continuation followed those notes in the corpus. The order is how many notes back the machine remembers; order nought knows only how common each note is. When a context was never seen, it falls back to shorter ones, as Part 14's model of the next note did. And to compose, draw a note from the counts, append it, and repeat.
How good is each order? Measure it on the tunes kept back, in bits per note: how surprised the model is by each note Bach actually wrote. Order nought needs bits a note; remembering one note brings it to ; two notes, , the best. Beyond that the curve rises again. Longer contexts are rarer: most four-note contexts in a new tune were seen once or never, and what was seen once is a poor guide. In this corpus and estimator, higher orders beyond the best generalize less well.
Bits per note is an average; note by note it shows where the music surprises. Here is a tune kept back, and how many bits the order-two chain needed for each of its notes. Inside a phrase most notes are cheap. The expensive ones sit at the boundaries: the note that ends a phrase, bits on average against overall, because the machine must decide that the phrase ends there, and the note that begins the next, which can start almost anywhere. Phrase boundaries can also affect listeners' expectations, though this model score is not a direct perceptual measurement.
Hear the first two phrases of a tune drawn from orders one, two and eight.
Order one wanders: every step is plausible, and the whole goes nowhere. Order two sounds more like a hymn. Order eight sounds most like Bach of all. The next chapter shows why that is not the compliment it seems.
3Novelty and copyingFoundations2 min
When does learning from Bach become copying Bach?
Measure copying directly. For each of twenty tunes from each order, find the longest run of notes that appears, note for note, in some training tune, and the share of its notes that sit inside a copied run of eight. Order one copies runs of about notes, and almost nothing of eight. Order eight copies runs of notes, and per cent of everything it writes is inside a copied run of eight. And the yardstick: Bach's own tunes, the ones kept back, measured the same way against the training tunes. They share runs of about notes, and per cent: hymn tunes share their stock phrases, and cadences most of all.
Hear it. The longest copied stretch of an order-eight tune, then the opening of the chorale it came from.
notes in a row, note for note, from . With eight notes of memory and only a few thousand notes to learn from, most contexts have been seen once, in one tune, and the fitted chain strongly favours following that tune until backoff or a branch changes it. Much of this particular output reproduces a training melody.
Put the two measures together: copying across, prediction of new tunes up, one dot for each order. Here low order has shorter copied runs and high order longer ones. Coherence is not measured directly. The order that predicts new tunes best, order two, copies a little less than Bach's own tunes share with one another, and order three a good deal more. Good held-out prediction alone does not rule out copying, and these particular models illustrate one relationship; copied runs and held-out prediction do not prove a universal quality-novelty frontier. Alexandre Papadopoulos, Pierre Roy and François Pachet built Markov generators that forbid copying beyond a chosen length, by construction.
4ConstraintsFoundations2 min
Can a chain be told where to end without losing its style?
A chain draws one note at a time, without additional conditioning it does not enforce an ending. Suppose we want thirty-two notes that end, as a chorale does, on a long tonic under a fermata, with every phrase ending on a note of the tonic chord. Draw freely and check: only per cent of draws pass. Drawing and throwing away is Hiller's method from 1957: correct, slow, and hopeless when the constraints get harder. Better to change the chain so that it can only draw what passes, while keeping its odds otherwise.
The trick is to count backwards first. For every state of the chain and every number of notes still to come, compute the probability that a legal ending can still be reached from there. It needs only the chain's own probabilities, summed backwards from the end. Then draw forwards, weighting each candidate note by its probability times its chance of still ending well. With positive feasible mass and exact backward probabilities, the conditional sampler avoids dead ends. And the result is exactly the chain's own distribution, conditioned on the constraints; François Pachet and Pierre Roy showed how in 2011.
Hear thirty-two notes from the same order-two chain, drawn freely, then under the constraints.
The free draw stops in mid-air, on whatever note its thirty-second happened to be. The constrained one closes as a chorale closes, on a long C, and its longest copied run is still only notes: the constraints shaped where it went without making it copy.
5RecombinationFoundations2 min
What if the machine copies on purpose, a phrase at a time?
David Cope's EMI took the opposite road. Cut a composer's works into pieces and put them back together differently. The pieces join where they connect: the last note of one leads by step to the first of the next. Patterns the composer repeats, which Cope called signatures, are kept whole. And an analysis of each piece's role, opening, middle or cadence, decides where it may go. The approach recombines learned material; the extent of literal copying and novelty depends on the implementation and source corpus.
Monochord's recombiner takes an opening phrase from one chorale, two middle phrases from two others, and a closing phrase from a fourth, each joined to the next by a step, and Part 17 harmonizes the result.
It sounds like a chorale because every phrase is one: per cent of its notes lie inside a run of eight copied from a single chorale, and its longest copied run, notes, is a whole phrase. Only the joins are new.
Is it composing? Cope's chorales and inventions in Bach's style convinced listeners, and his critics said the convincing parts were Bach's. Cope answered that every composer recombines what they have heard, and that EMI only does it openly. Both are partly right: style is largely the recombination of shared patterns, as Parts 25 and 26 found for the Baroque and the Classical style, and the order is where the art is. For the law, protectable expression, substantial similarity and jurisdiction matter, alongside what and how much is copied: a phrase of a living songwriter's melody is not a stock cadence of Bach's.
6Music as tokensPractice2 min
How do you turn a score into words for a language model?
A language model reads tokens, so music must become tokens, and the choice matters. Here is a chorale's opening three ways. One token a note, pitch, length and phrase end together: different symbols, about tokens a tune. Pitch, then length, as separate tokens, the way MIDI-like encodings do: only symbols, but tokens a tune. Or a grid, one token every sixteenth note, with a symbol for holding, similar to the sixteenth-note grid used by DeepBach: symbols, and tokens a tune.
What does the choice trade? Fewer symbols make longer sequences: each symbol is seen more often, but the model must look further back. A grid makes time explicit and simultaneous notes easy, four voices on one grid; events make long notes cheap. For many instruments there are encodings with bars and positions as tokens, like REMI in 2020, or each instrument's notes interleaved. Or skip symbols altogether, and use tokens from a neural codec of the audio itself, the subject of Part 66. Monochord's transformer reads a pitch, then a length, then a fermata if the phrase ends: sixty-one symbols, with a bounded MIDI range and duration vocabulary.
One more choice concerns keys. Every tune here is in C, so a model that sees only C learns C's pitches, not the tune's intervals. But the same tune a tone higher is, to a listener, the same tune: transposition makes a free example. So a model can learn from each tune in twelve keys, as the transformer of the next chapter will. It is not quite free: a voice's range, or an instrument's open strings, make some keys rarer and some sounds unlike the others. Tokens that are themselves intervals build the symmetry in, instead of teaching it by example.
7A transformerFoundations3 min
Can a network do better than counting, with so little music?
Now a network. It is the pocket transformer of AI, Built: each token attends to everything before it, positions are rotations, and there are three layers. It has about thousand weights, trained to predict the next token, exactly as a language model is. The training tunes alone make only thousand tokens, far fewer than the weights. So train a second copy on each tune in twelve keys, transposed: thousand tokens, by the old trick of data augmentation. A few tunes are kept aside to watch during training; the test tunes are touched only at the end.
Watch both learn, scored on the tunes set aside. On the tunes alone the loss falls, then turns round near step and climbs: the network has begun to learn its training tunes by heart, and the held-out loss increases after its best point in this run. In twelve keys it turns later, near step : no single key's tunes can be memorized as fast, which encourages useful transposition-related patterns; the curves alone do not prove what representation it learned. Each model is kept as it was where the tunes set aside said to stop.
On the test tunes the best counting model needs bits a note. The transformer trained on the tunes alone, stopped at its best, needs . In twelve keys, : better, and it the order-two chain. With a few thousand notes to learn from, the network has little room to show what it can do; the field's networks learn from many thousands of pieces, where counting cannot follow.
The memorizing is audible. Hear a tune from the network trained on the tunes alone for all fifteen hundred steps, far past where it should have stopped, then the chorale it copies most.
notes in a row from . A network can memorize as an order-eight chain does, and more quietly: nothing in its weights says which tune it is reciting. Large music and language models have been shown to reproduce training data word for word, and measuring this is now part of how they are tested.
And the network trained in twelve keys, composing from nothing: the first three tunes it drew, two phrases each. Because it learnt every key, it chooses one each time.
Their longest copied runs are and notes. They move like hymn tunes and end their phrases where hymn tunes do; these exact-run checks find no long match in the comparison corpus, which does not establish originality against all existing music.
8TemperatureFoundations2 min
How adventurous should a machine be?
Every generator here draws from a distribution, and one knob reshapes it: the temperature. Raise each probability to the power one over the temperature, and renormalize. Below one, the likeliest note grows likelier still: safe, repetitive. At one, the model's own odds. Above one, the unlikely notes, the F sharp in C major, get their chance: adventurous, and soon lost.
Your turn. The opening phrase of a chorale the network never saw, three times, each continued by the transformer at a different temperature: a half, one, and one and a half. Can you tell which is which?
They were in order: a half, one, one and a half. Cooler draws keep to the likeliest notes and the key; hotter ones take more of the unlikely ones, as the measures on the next page show over many openings.
Measure it over the held-out openings, each continued twice at each temperature. The intervals come closest to Bach's at temperature one, bits away, against when cooler and when hotter: at one the model draws with its own odds, which were fitted to music like Bach's. Notes outside the key rise with the temperature, from to per cent, where Bach's tunes have ; and phrases end on the tonic chord most often when it is cool. Copying stays near nothing at every temperature: this model, stopped at its best, shows little exact eight-note-run copying in these finite trials. No setting is right for every purpose; people who use such models tune it by ear.
Temperature is one of several ways to draw. Top-k draws only among the k likeliest notes. Nucleus sampling, from Ari Holtzman and colleagues, draws among the likeliest notes that together hold a chosen share of the probability. Beam search approximately searches for high-probability sequences; it need not find the global optimum and can favour repetition. All of them trade surprise for safety, and none adds knowledge the model does not have.
9Four partsFoundations3 min
How does a machine write all four voices of a chorale?
A chorale has four voices, and a machine that writes them all must keep each voice singable and every chord right. DeepBach, from Gaëtan Hadjeres, François Pachet and Frank Nielsen in 2017, puts the four voices on a grid of sixteenths. A network learns to predict each voice's note at one moment from everything around it, past and future, in all four voices. To compose, start from random notes and repeatedly resample individual notes: a pseudo-Gibbs procedure, since learned conditionals need not define a consistent joint distribution. Any note can be fixed in advance, a melody, a cadence, a bass, and the rest fills in around it. In its listening test, many listeners took its chorales for Bach's.
Monochord does it in two steps. The transformer writes the tune, and Part 17's harmonizer writes the other three voices. Part 17's harmonizer chooses chords learnt from Bach's chorales and voicings by dynamic programming under the rules of voice leading. It is a pipeline, not a joint model: the tune cannot bend to suit the harmony, as Bach's tunes sometimes bend. But every chord it writes can be checked: ranges, spacing, parallel fifths and octaves.
Here is a tune the transformer wrote, harmonized in four parts by Part 17: the first of its draws that stayed in C major and that Part 17 could harmonize; earlier draws strayed from the key or could not be fitted.
chords, with parallel fifths or octaves between them, and a tune whose longest copied run is notes. It passes these implemented checks and may sound plausible; the checks do not establish comprehensive stylistic correctness. Whether it is good is a question the next chapter takes seriously.
How good is the harmonizer? Hear a tune held out from the melody generators; the Part 17 chord model uses the broader corpus, harmonized by Bach, then by Part 17's search.
Bach's inner voices move: passing notes, suspensions, a bass with a line of its own. Part 17's move by the beat, one chord to each, correct and plain. Part 17 measured the gap: its chords agree with Bach's on many beats, and its texture is simpler everywhere. A joint model like DeepBach learns the decorations too.
10Judging machinesPractice3 min
How do you tell whether a composing machine is any good?
Your turn. Two machine tunes, harmonized the same way. One is mostly copied from Bach, note for note; the other is not. Which is the copy?
The second was the copy: an order-eight chain, per cent of it inside runs copied from Bach. The first, from the transformer, per cent. If you could not tell, that is the point: copying can be hard to identify by ear without knowing the source, so it has to be measured.
Put every machine before the same judges, twenty tunes each, beside Bach's own tunes kept back. How far its melodic intervals are from Bach's; how often its phrases end on the tonic chord; how much of it is copied. On intervals and cadences every machine is close to Bach, even order one, and the recombiner closest of all. Only the copying column tells them apart: per cent copied for order eight, for the recombiner, for the transformer, whose intervals are the furthest from Bach's, bits. No single number ranks them; a table like this one, with the copying column always in it, is the least an honest report needs.
Each judge has its traps. Statistics can be matched by copying: every judge here rewards a perfect copy of Bach, except the copying column. Likelihood on unseen music rewards prediction, not quality: a model can predict well and compose dully. Cherry-picking: the best of a hundred samples says little about the hundredth, and demonstrations are usually the best. Could-listeners-tell tests depend on who listens, how long the excerpt is, and what it is set beside. So report uncurated samples, likelihood on music the model never saw, how much is copied, and a listening test with its design.
And listening tests. A Turing-style test asks only whether the machine passes for a person, as the hook of this part did. Better to rate qualities, coherence, interest and style, blind, against real music of the same kind. Experts and novices hear differently, so say who listened, as Part 58's listening tests did. And long-range form is another important property to evaluate, so judge whole pieces, not eight bars.
11Frontier: form, control and attributionResearch2 min
What do composing machines still not do?
Three frontiers. The first is form. The Music Transformer of 2018, from Cheng-Zhi Anna Huang and colleagues, uses relative positional attention to help represent relationships across time; transposition invariance does not follow from relative positions alone. It wrote a minute of coherent piano music, learnt from performances; but the plan of a sonata across twenty minutes is still hard. Hierarchy helps: plan the sections, then the phrases, then the notes, as in Part 21's forms. Monochord's tunes end where their phrases end, and none of them knows where it is in a piece.
The second is control. Condition the model on a key, a tempo, chords, a style or a sentence, or ask it to fill a gap in the middle of a piece. Many of the most useful systems are tools for composers rather than replacements: suggest the next bar, harmonize a line, vary a motive. And constraints, as in Chapter 4: say what must be true, and sample everything else.
The third is attribution. Whose music is in a model's output? Copying can be measured, as this part measured it, but only against data one has. And influence is subtler than copying: which training pieces made this phrase likely? Bach is long out of copyright; training corpora can contain protected music, depending on the model and its dataset, as Part 60's rights and Part 66's courts make clear. How training data should be attributed and licensed is being argued now.
A research problem to end on. Train generators of many sizes on a corpus whose every piece is known. Measure, for each, its likelihood on unseen music and how much it copies, by exact runs and by near matches. Ask listeners which outputs they prefer, without telling them which is which. Is there a frontier of novelty against quality, and can a model be moved along it, or past it? The answer would tell us what to ask of composing machines, and of their training data.
Variation 65, recap and problemsAll tracks2 min
Every part ends by doing something to the Tune with what it built. Here the transformer hears the Tune's first phrase and continues it, once at each of five temperatures, from a quarter to one and a half. These are the first draws, uncurated: what the machine wrote, not what we liked.
Row sixty-five of the ledger: five temperatures, and the longest run any continuation copied from Bach, notes. The Tune is not a chorale, and the machine, which knows only chorales, answers it in the only language it has.
What did we find? Composing machines follow rules, shape chance, or learn statistics from music. A Markov chain's order trades prediction for copying, and order two predicts these held-out melodies best among the tested counting models. Order eight copies whole chorales, where Bach's own tunes share about a tenth of their notes in copied runs. Constraints let a chain sample exactly what must be true, and recombination copies on purpose. A small transformer, given little music, memorizes; transposition augmentation improves held-out prediction in this experiment, without eliminating memorization in general. And a composing machine should be judged by uncurated samples, likelihood, copying and listeners together.
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 generative audio, where the same next-token idea runs on sound itself. In research, with evaluation, leakage and listening tests. And in the concert at the end, where some Variations were made by machines, and are labelled so.
And in practice. Split data by work, because the same tune twice is a test already seen. Measure copying, with real music's copying beside it. Show uncurated output, and say how many samples there were. And know the data: whose music trained the model, and on what terms.
The books and papers this part follows. The full list, with notes, is in the README.
Where it goes next. The same next-token idea on sound itself in Part 66; evaluation, leakage and listening tests in Part 67; machine-made Variations, labelled, in the concert of Part 68.
Key results
The part's results in one place, for revision.
Try it
Lab 65 · Machines that compose, computed
Train Markov chains of orders 0 to 6 on Bach's chorale melodies, split by hymn tune; measure bits per note on tunes kept back and how much each order's tunes copy; then sample a chain under constraints and hear the orders.
python -m videos.music.labs 65
needs numpy, scipy, matplotlib · download lab65.py ·
source on GitHubchorale tunes (major, 4/4); different hymn tunes; learn from; kept back 163; 114; 132; 23
order 0: bits per note on new tunes; share inside a copied run of 8 5.22; 0%
order 1: bits per note on new tunes; share inside a copied run of 8 3.57; 0%
order 2: bits per note on new tunes; share inside a copied run of 8 3.40; 5%
order 3: bits per note on new tunes; share inside a copied run of 8 3.53; 28%
order 4: bits per note on new tunes; share inside a copied run of 8 3.68; 68%
order 6: bits per note on new tunes; share inside a copied run of 8 3.83; 92%
Bach's own tunes kept back, measured the same way 11%
a free 32-note draw ends legally with probability 0.66%
ear problem: tunes from several orders, shuffled; which order was each? (listen first) 3, 6, 4, 1, 2
A chain that remembers little predicts new tunes poorly and copies nothing; one that remembers much predicts them poorly too, because it copies; the best predictor sits between, near how much Bach's tunes share.
The code (76 lines; it asserts its own result)
"""Lab 65: machines that compose, computed: Markov chains of several orders on Bach's chorale tunes, scored by how
well they predict tunes they never saw and by how much of what they write is copied; and a chain sampled exactly under
constraints."""
import numpy as np
from videos.coursekit import labs
from explainer.music.monochord import SR, Clip, concat
from explainer.music.monochord import machines as M
from explainer.music.monochord.partkit import organ_tone
TITLE = "Machines that compose, computed"
GOAL = ("Train Markov chains of orders 0 to 6 on Bach's chorale melodies, split by hymn tune; measure bits per note on "
"tunes kept back and how much each order's tunes copy; then sample a chain under constraints and hear the orders.")
TASKS = [
"Change ORDERS. Where does prediction of new tunes stop improving, and where does copying take over?",
"Change RUN, the copied-run length that counts as copying. Is Bach's own share of copying still small at RUN = 5?",
"Change LENGTH, the constrained tune's length. How rare do legal endings become for a free draw?",
]
ORDERS = [0, 1, 2, 3, 4, 6]
RUN = 8
LENGTH = 32
def play(notes, sixteenth=0.15):
t = sum(d for _, d, _ in notes) * sixteenth + 0.6
y = np.zeros(int(t * SR))
k = 0.0
for p, d, f in notes:
z = organ_tone(440 * 2 ** ((p - 69) / 12), d * sixteenth * (1.6 if f else 0.95), partials=6, rolloff=0.7)
i = int(k * SR)
y[i:i + len(z)] += z[: len(y) - i]
k += d * sixteenth + (0.3 if f else 0.0)
return Clip(y[: int((k + 0.5) * SR)] / (np.max(np.abs(y)) + 1e-12) * 0.8, SR)
def run(seed=0):
rng = np.random.default_rng(seed)
lab = labs.Lab()
ts = M.tunes()
train, test = M.split(ts, 0.2, seed=seed)
grams = M.train_grams(train)
lab.row("chorale tunes (major, 4/4); different hymn tunes; learn from; kept back", f"{len(ts)}; {len({t['group'] for t in ts})}; {len(train)}; {len(test)}")
bits, share = {}, {}
for o in ORDERS:
m = M.Markov(o).fit(train)
bits[o] = m.bits(test)
share[o] = float(np.mean([M.copied_share(m.sample(seed=s), grams, RUN) for s in range(8)]))
lab.row(f"order {o}: bits per note on new tunes; share inside a copied run of {RUN}", f"{bits[o]:.2f}; {100 * share[o]:.0f}%")
bach = float(np.mean([M.copied_share(t["notes"], grams, RUN) for t in test]))
lab.row(f"Bach's own tunes kept back, measured the same way", f"{100 * bach:.0f}%")
best = min(bits, key=bits.get)
assert 0 < best < max(ORDERS) # a middle order predicts new tunes best
if max(ORDERS) >= 6 and RUN == 8:
assert share[max(ORDERS)] > 0.6 > bach # long memory copies; Bach's tunes mostly do not
r = M.constrained(train, length=LENGTH, seed=seed)
x = r["notes"]
assert len(x) == LENGTH and x[-1][2] and x[-1][0] % 12 == 0
lab.row(f"a free {LENGTH}-note draw ends legally with probability", f"{100 * r['p_legal']:.2f}%")
order = list(rng.permutation(ORDERS[1:]))
clips = [play(M.phrases(M.Markov(o).fit(train).sample(seed=seed + 1))[0] + M.phrases(M.Markov(o).fit(train).sample(seed=seed + 1))[1]) for o in order]
lab.audio = concat(clips, gap=0.8)
lab.row("ear problem: tunes from several orders, shuffled; which order was each? (listen first)", ", ".join(str(o) for o in order))
fig, (ax1, ax2) = labs.figure(2)
ax1.plot(ORDERS, [bits[o] for o in ORDERS], "o-", color=labs.GOLD)
ax1.set_xlabel("order")
ax1.set_ylabel("bits per note, new tunes")
ax2.plot(ORDERS, [100 * share[o] for o in ORDERS], "o-", color=labs.GOLD, label="chain")
ax2.axhline(100 * bach, color="0.6", ls="--", label="Bach kept back")
ax2.set_xlabel("order")
ax2.set_ylabel(f"% inside a copied run of {RUN}")
ax2.legend(fontsize=7)
lab.fig = fig
lab.note = ("A chain that remembers little predicts new tunes poorly and copies nothing; one that remembers much predicts "
"them poorly too, because it copies; the best predictor sits between, near how much Bach's tunes share.")
return lab
Now change it
- Change ORDERS. Where does prediction of new tunes stop improving, and where does copying take over?
- Change RUN, the copied-run length that counts as copying. Is Bach's own share of copying still small at RUN = 5?
- Change LENGTH, the constrained tune's length. How rare do legal endings become for a free draw?
Problems, with solutions
Try each problem before opening its solution.
-
Compute. A corpus has 7,000 notes and 146 distinct notes. Roughly how many order-3 contexts are possible, and how many can it have seen?
Solution
146³ ≈ 3.1 million contexts of three notes are possible; the corpus has at most about 7,000 positions, so it can have seen at most 7,000 contexts (fewer distinct ones), well under one in four hundred. Most order-3 contexts in a new tune have therefore been seen rarely or never, which is why order 3 already predicts worse than order 2.
-
Prove. Show that sampling forward with weights P(x | s) β_{k−1}(s′) draws exactly from the chain conditioned on the constraints.
Solution
By induction, β_k(s) is the probability, under the chain, that the next k notes from s satisfy the constraints. The conditional probability of the next note x given s and given that the constraints will hold is P(x | s) β_{k−1}(s′) / β_k(s), by Bayes' rule; drawing x with weights P(x | s) β_{k−1}(s′) draws from exactly this. Multiplying the conditionals along the sequence gives P(sequence) / P(constraints hold) for every legal sequence and 0 for every other: the chain conditioned on the constraints.
-
Ear. The lab plays tunes from orders 1 to 6 in random order; rank them by how Bach-like they sound, then check how much each copied.
Solution
The lab prints the orders and, for each order, the share inside copied runs. If the tunes you ranked most Bach-like came from the high orders, the copying column shows why: they are Bach's.
-
Build. Add a maximum-order constraint: forbid any run of more than 6 notes copied from one tune, and measure the cost in bits.
Where to look. Papadopoulos, Roy and Pachet (2014) build an automaton of the forbidden runs and sample the chain intersected with it; a simpler version rejects, at each step, any note that would complete a copied run of seven (a suffix check against
train_grams), and backs off when nothing is left. Measure bits per note of the constrained sampler's own distribution on the test tunes, and the copying, against the unconstrained chain. -
★ Is there a frontier of novelty against quality, and can a model be moved past it?
Where the frontier is. Train generators of many sizes on a corpus whose every piece is known; measure likelihood on unseen music and copying by exact and near matches; collect blind preferences; ask whether any training method (more data, augmentation, constraints, retrieval) moves a model past the curve the others share.
Notes and sources
Sources
- J.-P. Briot, G. Hadjeres and F.-D. Pachet, Deep Learning Techniques for Music Generation (2020); G. Nierhaus, Algorithmic Composition (2009).
- L. A. Hiller and L. M. Isaacson, Experimental Music (1959); I. Xenakis, Formalized Music (1971); D. Cope, Experiments in Musical Intelligence (1996) and Virtual Music (2001), with D. Hofstadter, "Staring Emmy straight in the eye".
- M. T. Pearce, The Construction and Evaluation of Statistical Models of Melodic Structure (thesis, 2005); F. Pachet and P. Roy, "Markov constraints: steerable generation of Markov sequences", Constraints (2011); A. Papadopoulos, P. Roy and F. Pachet, "Avoiding plagiarism in Markov sequence generation" (AAAI, 2014).
- G. Hadjeres, F. Pachet and F. Nielsen, "DeepBach: a steerable model for Bach chorales generation" (ICML, 2017); C.-Z. A. Huang et al., "Music Transformer" (ICLR, 2019); Y.-S. Huang and Y.-H. Yang, "Pop Music Transformer" (REMI, ACM Multimedia, 2020); A. Holtzman et al., "The curious case of neural text degeneration" (ICLR, 2020).
- L.-C. Yang and A. Lerch, "On the evaluation of generative models in music", Neural Computing and Applications (2020).
Review scope: tune-group holdouts apply to the melody generators. The separate Part 17 chord harmonizer uses its broader chorale corpus. Exact-run comparisons only measure copying against the supplied reference corpus.
About this partfrom its README
Part 65 of a sixty-eight-part course in music (see the series plan and
the syllabus), the fifth part of Act XI, Listening Machines. In 1997 an audience in Oregon heard three
pieces, one by Bach, one by a professor in Bach's style and one by David Cope's program EMI, and, as it was reported, took
the program's for Bach's. This part builds composing machines that learn from music, from a Markov chain to a small
transformer, on the melodies of Bach's chorales, and measures relationships between copying and held-out prediction in these specific models, without treating prediction as a direct measure of coherence. The tools are Monochord's (explainer/music/monochord/machines.py, on Part 17's chorale table and
harmonizer and AI, Built's pocket transformer); every generated tune is checked against the training tunes for copying.
- Bach, a professor and a program. An ear question (three pairs of harmonized chorale phrases: which is Bach's? the second, BWV 166.6, never seen by the machines; the others a Markov chain's and a transformer's, each the first draw that stayed in the key and could be harmonized); Hofstadter's concert in Eugene; the plan.
- 1. Dice, rules and chance. Composing machines from the dice minuet (1792) to the Music Transformer (2018); rules, chance and statistics; the corpus (364 chorales; 163 in major keys and 4/4, transposed to C; only 114 different hymn tunes, so split by tune: 132 chorales to learn from, 23 tunes kept back), a chorale heard.
- 2. Counting what comes next. Variable-order Markov chains; bits per note on the tunes kept back by order (5.22 at order 0, 3.40 at order 2, the best, 3.83 at order 8); where a tune surprises (at the phrase boundaries); orders 1, 2 and 8 heard.
- 3. Novelty and copying. Longest copied run and share inside copied runs of eight, by order (order 1: 4.9 notes and none; order 8: 26 notes and 91 %), against Bach's own tunes kept back (8.2 and 11 %); an order-8 tune's 40-note copy of BWV 226.2, heard beside it; the trade, prediction against copying.
- 4. Constraints. A chain cannot plan an ending (0.66 % of free 32-note draws end legally); backward messages and forward sampling (Pachet and Roy, 2011); free and constrained draws heard.
- 5. Recombination. Cope's recombinancy; four phrases from four chorales joined by steps and harmonized, heard (79 % inside copied runs; only the joins are new); is it composing?
- 6. Music as tokens. A chorale's opening three ways (146 note tokens; 34 pitch-and-length symbols; a 27-symbol grid); what the choice trades.
- 7. A transformer. AI, Built's pocket transformer (344,160 weights) on 13,487 tokens, and on the same tunes in twelve keys (161,844); training curves on tunes set aside (the tunes-alone model turns round near step 100, the twelve-key one near 300); bits on the test tunes (3.76 and 3.49, against the order-2 chain's 3.40); a network trained too long recites 40 notes of BWV 322, heard; the first three tunes it draws from nothing, heard.
- 8. Temperature. Reshaping the odds; an ear question (one opening continued at 0.5, 1.0 and 1.5: in order); over 46 continuations each, intervals closest to Bach's at 1.0, notes outside the key from 6 to 19 % (Bach 2 %), cadences on the tonic chord most often when cool, copying near none; top-k, nucleus and beam search.
- 9. Four parts. DeepBach and pseudo-Gibbs sampling; Monochord's pipeline (the transformer's tune, Part 17's harmony); a machine's chorale heard (no parallel fifths or octaves); Bach's harmony beside Part 17's on a tune kept back, heard.
- 10. Judging machines. An ear question (which is copied? the second, an order-8 chain's, every note inside a copied run); every machine before the same judges (only copying separates them); pitfalls; listening tests.
- 11. Frontier: form, control and attribution. Relative attention and long-range form; control and infilling; attribution and training data; ★ research problem: is there a frontier of novelty against quality, and can a model be moved past it?
- Variation 65, recap and problems. The Tune's first phrase continued by the transformer at five temperatures, one draw each, uncurated (longest copied run 4 notes); the ledger; what we found; five problems; where it comes back; in practice; references; Part 66.
What is computed and built
python -m videos.music.music65.compute (some minutes: four transformer runs, two long and two stopped where the tunes set
aside say) fills .cache/music65/.
| Item | What it computes | Checked against |
|---|---|---|
corpus |
the tunes, the split by hymn tune, three representations | the chorale table (tests) |
markov, surprise, copy |
bits per note by order; surprise note by note; copying by order and Bach's own | the training tunes (tests) |
constrained, recombine |
an order-2 chain sampled exactly under constraints; recombined phrases | the constraints; the sources (tests) |
transformer, samples |
two transformers, curves, bits, copying; an overtrained one reciting | the test tunes; the training tunes (tests) |
temperature, judge, copyquiz |
continuations at three temperatures; every machine judged alike | held-out Bach (tests) |
harmony, bachvs17, hook |
tunes harmonized by Part 17; Bach beside Part 17 | the voice-leading rules (tests) |
tune65 |
Variation 65 | the training tunes (tests) |
Monochord's tools are held in tests/music/test_machines.py; this part's claims and clips in tests/music/test_music65.py.
Sounds. Every tune is played on Part 17's organ tones, with Part 17's fermata pauses; harmonized tunes use Part 17's
chord model and voice-leading search. Bach's chorales are in the public domain; the table keeps only pitches, times and
fermatas (see explainer/music/monochord/chorales.py).
What the models are, and are not. The corpus is small: 6,937 notes of melody, so every model here is data-starved, and the transformer's comparison with counting says more about small data than about transformers. The best order is a property of the split as well as of the music: Part 67 re-ran it over ten splits by tune, and order 2 was best in 7, order 1 in 3, with order 2's bits per note ranging from 3.40 to 4.16. The Markov chains blend orders by PPM's escape method, over whole notes. The transformer is three layers and 96 dimensions, trained without dropout; it is stopped where loss on nine tunes set aside from the training tunes was lowest. Copying is measured by exact runs; near copies (a note changed, a rhythm altered) are not counted, so these numbers are lower bounds. Draws shown harmonized are the first that stayed in the key and could be harmonized, as the film says.
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- Hook: an ear question (which is Bach's?); Hofstadter's concert; the plan.
- Dice, rules and chance: composing machines from 1792 to 2018; three kinds; the corpus split by hymn tune, heard.
- Counting what comes next: Markov chains; bits per note by order; where a tune surprises; three orders, heard.
- Novelty and copying: copying by order against Bach's own; an order-8 copy beside its source, heard; the trade.
- Constraints: why a chain cannot plan; backward messages; free and constrained, heard.
- Recombination: Cope's recombinancy; four chorales in one tune, heard; is it composing?
- Music as tokens: three representations; what the choice trades.
- A transformer: design; training curves; bits against counting; a network that recites, heard; its tunes, heard.
- Temperature: reshaping the odds; an ear question (three temperatures); the measures; other ways to draw.
- Four parts: DeepBach; Monochord's pipeline; a machine's chorale, heard; Bach beside Part 17, heard.
- Judging machines: an ear question (which is copied?); every machine, the same judges; pitfalls; listening tests.
- Frontier: long-range form; control; attribution; the research problem.
- Variation 65: the Tune's first phrase continued at five temperatures, uncurated. Outro: problems, payoffs.
Covers: n-gram models and the novelty-plagiarism curve; constraints; recombination; token representations;
DeepBach's sampling; the Music Transformer's relative attention; temperature and its kin; control; evaluation and its
pitfalls; memorization.
Built and computed: monochord/machines.py on Bach's major chorale tunes (163, 114 hymn tunes, split by tune):
Markov orders 0–8 (3.40 bits a note at order 2, the best); copying by order (order 8: runs of 26 notes, 91 % copied;
Bach's own tunes 11 %); exact constrained sampling (0.66 % of free draws end legally); recombination; AI, Built's
pocket transformer, with and without transposed copies (3.76 and 3.49 bits; trained too long, it recites 40 notes);
temperature (intervals closest to Bach at 1.0); harmonized by Part 17 with no parallels.
Variation 65: the Tune's first phrase continued at five temperatures, uncurated and labelled.
Frontier: long-range form; control; attribution.
Reading: Hiller & Isaacson; Cope; Pachet & Roy (2011); Hadjeres et al. (2017); Huang et al. (2018); Briot et al.,
Deep Learning Techniques for Music Generation.
Build the film
python -m videos.music.music65.compute # the part's numbers, into .cache/music65
python tools/build.py music65 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py music65 Hook # one chapter, silent, with a contact sheet
Scenes: videos/music/music65. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
python -m videos.music.music65.compute # numbers and sounds (the transformers train)
EXPLAINER_TTS=silent python tools/build.py music65 -q l --fps 15 # a silent-narration preview, with the sounds
python tools/qa_sound.py music65 --sync # the sound gates
python tools/dead_air.py renders/music65_480p.mp4 --sound music65 # no empty screen; no sound over a still one
python tools/lecture_length.py music65 # 30 to 60 minutes, listening included
python tools/build.py music65 # 1080p30, narrated
python -m pytest -q tests/music # Monochord against its references; this part's claims and clips
python -m videos.music.labs 65 # the lab (writes a figure and a short WAV)