Harmonizing Bach chorales with a Transformer (a machine-learning side project)
This entry is not about number theory. In my spare time, I wrote ChoraleHarmonizer, a small program that takes a soprano melody and writes the three lower voices (alto, tenor, and bass) in the style of Johann Sebastian Bach’s four-part chorales. Bach left several hundred of these harmonizations, and writing the lower voices for a given melody is a classical exercise in music theory. So there is a lot of training data, and it is clear what a good answer looks like.
The model. The program uses a Transformer, the same kind of neural network as modern language models. It is trained on the four-part chorales in the music21 corpus, each transposed into all twelve keys. The music is written as text on a sixteenth-note grid. At each step, the sounding pitches are listed, the symbol _ holds the previous note, | marks a bar line, and ^ marks a fermata (the held notes at the end of each phrase). The soprano is part of the sequence that the model predicts, so at every position, the model knows the melody, the metre, and the phrase endings before it chooses the harmony. The network is small on purpose (about million parameters) and trained from scratch. Starting from a large text model would not help, since its vocabulary of words would be replaced by musical symbols anyway.
The network alone is not enough. For machine learning, a few thousand chorales are a very small dataset. On its own, the model writes harmony that sounds mostly right, but it often breaks textbook rules, above all the rule against parallel fifths and octaves, the worst mistake in chorale writing. So the interesting part of the project is not the network, but the layer of hand-coded classical music theory around it, which steers the generation. This “manual processing” turns a plausible imitation into an acceptable one.
The processing. Four things happen while the harmony is generated, from hard rules to soft preferences:
Constraints. The soprano and all structural symbols are fixed. Each lower voice stays in the range it has in Bach. At every fermata, all four voices must sound the cadence chord, as they do in over of Bach’s cadences.
Penalties during sampling. When a note is chosen, pitches that would form a parallel fifth or octave with a voice that is already written are penalized immediately. (This check alone reduces the parallel fifths from to per sixteenth notes, close to Bach’s .) Also, the inner voices are discouraged from repeating a note that they could hold instead.
Selection. For each phrase, the program samples several complete harmonizations and keeps the one that maximizes the model’s confidence minus a music-theory penalty. Since the best phrase is fixed before the next one is sampled, this explores exponentially many combinations at low cost.
Repair. Finally, the program finds the worst remaining rule violation, generates the harmony again from just before it, and keeps the result only if the total score improves.
Calibrating the rules. There are about twenty rules (parallel and hidden fifths, voice crossings and overlaps, augmented seconds, unresolved tritone leaps, doubled thirds, harmonic stagnation, and so on), but their penalties are not taken from a textbook. Each penalty depends on how much more often the raw model breaks the rule than Bach, measured on the corpus. Rules that Bach himself sometimes breaks cost little or nothing, so the penalties concentrate on the real weaknesses of the model. The exceptions also come from the data. If two “violations” almost always occur together in Bach’s chorales (for example a hidden fifth reached by similar motion, which he writes about forty times more often than expected by chance), they count as one violation instead of two.
Style presets. In addition to the rules, two statistics learned from the corpus judge each candidate harmonization as a whole. A harmonic model describes how the chord on each beat follows the previous one, and a texture model describes how often each voice should move. These models do not try to make the harmony as typical as possible, since this would lead to a bland, average Bach. Instead, each of them measures the distance from Bach’s median level of surprise, so a setting that is too predictable is penalized as well as one that is too wild. Moving this target gives the presets konservativ, ausgewogen, and kuehn (conservative, balanced, bold), which aim below, at, and above Bach’s median. So one can get anything from cautious textbook harmony to harmony that is bolder than Bach’s median, but always within the range of surprise that Bach actually used.
Trying it out. The code is on GitHub, and two commands are enough:
python bach_chorales.py # build the dataset from music21 (once)
python chorale_harmonizer.py # train, then harmonize the test chorales
With --presets konservativ,ausgewogen,kuehn, the program writes all three style variants of each chorale. If a trained model already exists, the training step is skipped. The folder output/ of the repository contains example outputs. For each test chorale, it has Bach’s original harmonization and the generated one (the three style variants where available), each as MIDI and MusicXML, so one can open them in any notation software and compare them bar by bar. All other settings (sampling temperature, search width, the rule weights) are in config.py.
Written with Claude. I wrote this project together with Claude, Anthropic’s AI assistant, over many iterations. In more than a hundred commits, we extended the list of rules, computed their weights from the data, added the search phrase by phrase, the repair step, and the style presets, and tried (and sometimes discarded) larger networks. It turned out that even a small machine-learning project like this one needs a lot of patient back-and-forth to get right.