Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Bach Chorale Generation: n-gram vs LSTM vs Transformer

A small, fully reproducible study of symbolic music generation. Four-voice Bach chorales are turned into token sequences, three language models are trained on the same data, and the pieces they generate are compared with real held-out Bach using both likelihood and music-theory metrics.

Kaggle notebook (reduced re-run of this pipeline): https://www.kaggle.com/code/abmaity/bach-chorale-generation

Main findings (details and caveats below)

  • On held-out chorales the LSTM has the best perplexity (2.55 ± 0.01), ahead of the Transformer (2.65 ± 0.02) and the 6-gram baseline (3.02). Mean over 3 seeds.
  • All three models learn voice ordering (soprano above alto above tenor above bass): generated pieces have about 2% voice crossings like real Bach (2%), against 45% for a control that only knows each voice's pitch distribution.
  • None of them learns the ban on parallel fifths and octaves: they produce 2.4 (n-gram), 5.3 (LSTM) and 7.5 (Transformer) per 100 steps versus 0.2 in real Bach. Lowering the sampling temperature helps but does not close the gap.
  • Likelihood and musical quality are not the same thing: the model with the best perplexity is not the best at counterpoint (the n-gram is).

Data and representation

  • Source: the Bach chorale collection shipped with music21 (corpus.chorales). 351 four-voice chorales were usable. Corpus files that did not have exactly 4 parts were skipped.
  • Transposition: every chorale is transposed to C major or A minor (shift of at most 6 semitones), and a <major> / <minor> token is placed at the start, so models do not have to learn 12 keys.
  • Grid: one step = one eighth note. Each step contributes four tokens: the pitch sounding in the soprano, alto, tenor and bass (or REST). Sequence = BOS, MODE, step_1(S,A,T,B), ..., step_n(S,A,T,B), EOS. Vocabulary: 58 tokens (6 special, the rest pitches seen in training).
  • Split: 80 / 10 / 10 by piece (seed 42): 280 train, 35 validation, 36 test chorales. No chorale appears in two splits, so the test numbers are not inflated by near-duplicate windows of the same piece.
  • Known simplification: a repeated note and a held note look identical (articulation is not modelled).

Models

All models predict the next token from the previous tokens and the voice of the token being predicted.

Model Details
n-gram Interpolated Witten-Bell smoothing, context = last n-1 tokens. Order chosen on validation loss (order 2: 2.92, order 3: 2.45, order 4: 2.05, order 6: 1.62, order 8: 1.71, order 12: 1.91).
LSTM Token + voice embeddings (128), 2 LSTM layers (256), dropout 0.3. AdamW, lr 2e-3, cosine decay.
Transformer Causal, pre-norm, 3 layers, d=128, 4 heads, ff=512, learned positions, dropout 0.2. AdamW, lr 3e-3, cosine decay.

Training: windows of 256 tokens, batch 16, at most 1,500 steps, early stopping on validation loss (patience 6 checks of 100 steps), best checkpoint kept. 3 seeds per neural model. Validation data was used for all choices (n-gram order, early stopping, Transformer learning rate); the test set was used only for the final numbers, with one disclosure below.

Honest note on tuning. The LSTM used the first learning rate I tried. The Transformer's first setting (lr 1e-3) badly underfit: validation 1.72 bits and test perplexity 3.25, worse than the n-gram. Raising lr to 3e-3 gave validation 1.40 bits. The first run's test result was printed next to its validation result, so I saw it before deciding to retune; the new setting was adopted because its validation loss was lower. That one change is the only tuning of the Transformer, and the earlier run is kept in runs/transformer_lr1e-3_s0/ and the dashed line below. The Transformer was still improving slowly when the 1,500-step cap and learning-rate schedule ended, so its gap to the LSTM may be smaller with more steps; I did not test that.

validation curves

Results

1. Held-out likelihood (36 test chorales)

Contexts are reset every 256 tokens for every model, so none gets longer context than the others.

Model Params Test bits/token Test perplexity Test top-1 acc.
6-gram (Witten-Bell, order chosen on validation) n/a 1.595 3.02 70.0%
LSTM (2 layers, 256 hidden) 944,698 1.351 ± 0.004 2.55 ± 0.01 71.8% ± 0.1
Transformer (3 layers, d=128) 651,706 1.407 ± 0.011 2.65 ± 0.02 68.5% ± 0.3

Perplexity is the effective number of equally likely choices per token (the vocabulary has 58 tokens). Neural rows are mean ± standard deviation over 3 training seeds. Note that the Transformer's top-1 accuracy is below the n-gram's even though its perplexity is better: its probabilities are better even though its single top guess is right less often.

2. Generated music vs real Bach

100 chorales per model per seed (60 eighth-note steps each, major/minor mixed 50/50), sampled with temperature 1.0 (T = 0.7 below). Mean ± std over 3 seeds (for the n-gram and the random control these are 3 sampling seeds of one fitted model); the "real" row uses non-overlapping 60-step windows from the held-out chorales. For these metrics, closer to the real row is better.

Temperature 1.0

Voice crossings Parallel 5ths/8ves per 100 steps Leaps > octave Out-of-key notes Exact 16-step copy
Real held-out Bach (42 windows) 2.0% 0.20 0.1% 3.4% 19%
Random (per-voice marginals) 44.6% 8.40 ± 0.46 9.2% 4.5% 0%
6-gram 1.5% 2.37 ± 0.21 0.3% 4.5% 0%
LSTM 2.0% 5.27 ± 0.40 0.9% 4.3% 0%
Transformer 2.1% 7.48 ± 1.06 0.3% 3.3% 0%

Temperature 0.7

Voice crossings Parallel 5ths/8ves per 100 steps Leaps > octave Out-of-key notes Exact 16-step copy
Real held-out Bach (42 windows) 2.0% 0.20 0.1% 3.4% 19%
Random (per-voice marginals) 34.1% 10.71 ± 0.17 5.0% 1.9% 0%
6-gram 0.6% 1.03 ± 0.11 0.1% 4.1% 0%
LSTM 0.4% 3.12 ± 0.46 0.2% 2.7% 1%
Transformer 0.6% 4.29 ± 0.21 0.0% 2.2% 0%

generation metrics

In the figure, solid bars are T = 1.0 and light bars are T = 0.7; the dashed line is real Bach.

Metric definitions (music_metrics.py, checked by tests/test_metrics.py on hand-made examples):

  • Voice crossings: share of steps, with all four voices sounding, where soprano ≥ alto ≥ tenor ≥ bass is violated.
  • Parallel 5ths/8ves: for each voice pair, consecutive steps where both voices move in the same direction and keep the same perfect fifth or octave/unison interval.
  • Leaps > octave: share of melodic moves larger than 12 semitones.
  • Out-of-key notes: share of notes outside C major / A minor (natural, harmonic and melodic).
  • Exact 16-step copy: share of pieces containing a 2-bar, four-voice passage that appears verbatim in the training set.

What the numbers do and do not say

  • Voice crossings, parallels and leaps separate the models from the random control. Out-of-key rate and pitch-class divergence do not: the control already matches each voice's pitch distribution, so those two are shown for completeness only.
  • No copying: 0% of generated pieces contain a 16-step verbatim passage from training, while 19% of real held-out windows do (chorales share tunes and phrases). So the models are not memorising, but they also do not reproduce the shared phrase structure of real Bach.
  • At T = 0.7 voice crossings drop below real Bach (the models become over-conservative) and parallels fall but stay well above real, so the counterpoint gap is not just sampling noise.

Limitations

  • Small data (351 chorales, 280 for training) and a single piece-level split; no variance over different splits.
  • 36 test chorales, so differences of a few hundredths of a bit are not meaningful. The LSTM-vs-n-gram gap is large and consistent across seeds; LSTM-vs-Transformer is smaller and depends on the training budget.
  • The metrics are proxies. No listening test was done. MIDI examples are in results/samples/ (3 per model plus real Bach); listen before drawing conclusions.
  • No articulation, no rhythm beyond the eighth-note grid, no chord or phrase conditioning, pieces are only 30 beats long.
  • The parallel-motion metric is a simplification of the counterpoint rule (it ignores, e.g., hidden fifths and the beat position).

Reproduce

pip install -r requirements.txt
python data.py                         # parse corpus -> data/chorales.json (about 1 min)
python train.py ngram
for s in 0 1 2; do
  python train.py lstm --seed $s --max_steps 1500
  python train.py transformer --seed $s --max_steps 1500 --lr 3e-3
done
python evaluate_all.py                 # T = 1.0   (about 4 min on 2 CPU cores)
python evaluate_all.py 0.7             # T = 0.7
python make_report.py                  # figures + this README

Everything ran on CPU (2 cores): about 4 minutes per LSTM run and 13 minutes per Transformer run.

Files

data.py corpus parsing, tokenisation, split | models.py n-gram, LSTM, Transformer | train.py training and early stopping | evaluate_lm.py held-out likelihood | generate.py sampling and MIDI export | music_metrics.py counterpoint metrics | evaluate_all.py full evaluation | make_report.py figures and README | runs/ per-run metrics and checkpoints | results/ JSON results, figures, MIDI samples | tests/ metric checks | notebooks/ Kaggle notebook and its builder.

References and credits

  • Corpus and parsing: M. S. Cuthbert and C. Ariza, music21: A Toolkit for Computer-Aided Musicology and Symbolic Music Data, ISMIR 2010.
  • Setup follows common practice for chorale modelling (e.g. the JSB Chorales benchmark and DeepBach by Hadjeres et al.); this repository is an independent small implementation, not a reproduction of those papers.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages