How it works

Notes on the method.

Twelve melody models so far, from a small LSTM to a 96 million parameter Transformer with six dials. This page is how they're built, what they learned from, how they're measured, and what went wrong along the way. It gets updated as the models do.

§ 1

Symbolic, not audio

Tools like Suno and Udio give you finished audio. A waveform, like a rendered photo. You can listen to it but you can't reach in and move a note, change a chord or rewrite the bridge.

The Melograph writes notes. MIDI, where every note is its own event with a pitch, a start time, a length and a loudness. Think of it as the difference between a screenshot and an SVG. One is flat pixels, the other is shapes you can pick up and move. So you can transpose a section, swap the instrument, nudge the timing, or drop the whole thing into Ableton or Logic and keep going.

Suno can trace its audio back into MIDI afterwards, the way you'd trace a photo into shapes, and it's about as lossy. Here it runs the other way. The model writes the notes, and the audio is a synth playing them. Swap the piano for a flute and nothing about the composition has changed.

Under the hood it's the same trick as a language model. The music is turned into a string of tokens, the model guesses the next token, and a new piece is sampled out one token at a time. It has never heard a sound. Everything it knows about which notes tend to follow which, how a phrase builds and where it lands, it learned from the symbols. The audio on this site is just a render of what it wrote.

§ 2

Prior work

Attention mechanisms for music

Huang et al. (2019) showed that attention picks up long-range musical structure better than a recurrent network does. Their Music Transformer learned relative positions rather than absolute ones, which makes musical sense. A fifth is a fifth whatever note you start on.

That paper is why op. 7 moved from an LSTM to a Transformer. The Melograph uses Rotary Position Embeddings [Su et al., 2021] rather than their relative-attention scheme. RoPE encodes position by rotating the query and key vectors, so attention fades with distance on its own, and it's cheaper.

REMI tokenisation

Huang and Yang (2020) introduced REMI (REvamped MIDI-derived Events), which turns music into typed tokens. Bar, Position, Pitch, Velocity, Duration, Tempo, Chord. A note stops being a single pitch token and becomes a little group saying when it happens, how loud, and for how long. It came in at op. 6 through the MidiTok library, with 32 velocity levels, chord detection, tempo tokens and rests.

Subword compression for music

Fradet et al. (2023) applied Byte Pair Encoding [Sennrich et al., 2016] to REMI sequences. The pairs of tokens that turn up together most often get merged into one, so a common note event becomes a single token and the model sees more music in the same window. In from op. 7 with a 512-token vocabulary, 1,024 in op. 8, 2,048 from op. 9 on.

Architectural components from language modelling

The rest of the Transformer is borrowed straight from language models. SwiGLU feed-forward layers [Shazeer, 2020], RMSNorm [Zhang and Sennrich, 2019], weight tying [Press and Wolf, 2017], and warmup-then-cosine learning-rate decay [Loshchilov and Hutter, 2016].

§ 3

How music becomes tokens

Three ways of turning music into tokens over the twelve models, each one carrying more of the music than the last.

Op. 1 was the first go, a proof of concept lost somewhere along the way. Everything here starts from op. 2.

OPP. 2–5

Pitch strings

Notes as pitch names ("C4", "F#3"), chords as dot-separated numbers. No timing, no loudness. Any sense of rhythm had to come from where a note sat in the sequence.

59–1,279

tokens

OP. 6

REMI

Typed tokens: Bar, Position, Pitch, Velocity (32 levels), Duration, Tempo, Chord, Rest. The vocabulary got smaller while carrying strictly more, because typed events beat listing every combination you ever saw.

362

tokens

OPP. 7–12

REMI + BPE

BPE merges token groups that keep turning up together, often a whole note event, into one token. A 256-token window covers two to three times the music raw REMI does. Op. 12 adds 43 attribute tokens on top for the dials.

512–2,091

tokens

§ 4

The instruments

MelodyLSTM

OPP. 1–6

A three-layer LSTM. The early ones had hidden layers of [256, 512, 256] and took the pitch in as a normalised float. Op. 5 widened that to [512, 512, 512]. Op. 6 swapped the float for a learned 128-dimensional embedding and was the first one built in PyTorch (the earlier ones were TensorFlow and Keras, converted later).

It reads 100 tokens at a time, one step apart, during training. To generate, it takes a seed phrase and keeps extending it through a sliding window.

MusicTransformer

OPP. 7–12

A decoder-only Transformer, the same shape as a small language model. Opp. 7 to 10 run 8 layers, 8 heads and a width of 512, about 34 million parameters. Opp. 11 and 12 go to 10 layers, 12 heads and 768 wide, about 96 million. Causal masking, and a KV cache so generating is quick.

RoPE

Position is encoded by rotating the query and key vectors, so attention fades with distance on its own.

SwiGLU

Gated feed-forward, W₂(SiLU(xW₁) ⊙ xW₃). Three projections instead of two, and a gate on what gets through.

RMSNorm

Pre-norm without mean centering, before both attention and feed-forward sublayers.

Weight tying

The input embeddings and the output layer share one set of weights. Fewer parameters, and it regularises for free.

§ 5

Training

The data pipeline

The MIDI files are split 90/10 into training and validation before any augmentation, so a transposed copy of a validation piece can never sneak into training. Since op. 11 the split is also group-aware, so two arrangements of the same song land on the same side. Augmentation is transposition within six semitones either way, up to two copies a file, which roughly triples the data without changing anything about how the music is put together.

Token sequences are cut into fixed windows. Length 100, one step apart, for the LSTM. Length 256, 64 apart, for the Transformer, which is scored on every position in the window.

Hyperparameters

LSTM · OP. 6

Layers3× LSTM [512, 512, 512]
Embedding128 dim
Sequence length100 · stride 1
Batch size256
Learning rate4e-3
OptimiserAdamW (wd 0.01)
ScheduleCosine annealing
Early stopping10 epochs patience

TRANSFORMER · OPP. 7/8

Layers8 blocks · 8 heads
d_model / d_ff512 / 2048 (SwiGLU)
Sequence length256 · stride 64
Batch size64 (accum 2)
Learning rate3e-4
OptimiserAdamW (wd 0.01)
ScheduleWarmup 2–4k + cosine
Early stopping15 epochs patience

Training data

StudyGenreTracksTokeniserVocab
Op. 2R&B / 90s hip-hop24Pitch strings59
Op. 3Dance~200Pitch strings635
Op. 4Jazz~120Pitch strings1,279
Op. 5Mixed275Pitch strings629
Op. 6Mixed275REMI362
Op. 7Mixed275REMI + BPE512
Op. 8Mixed + classical275 + MAESTROREMI + BPE1,024
Op. 9Nine styles, true melodies18,758REMI + BPE + style tokens2,048
Op. 10Nine styles, true melodies30,007REMI + BPE + style tokens2,048
Op. 11Nine styles, cleaned corpus91,373REMI + BPE + style tokens2,048
Op. 12Six measured attributes117,682REMI + BPE + attribute prefix2,091

Op. 8 adds the MAESTRO dataset (v3), 1,276 competition piano performances. Op. 12 adds the Nottingham, Essen and Meertens folk collections and the Weimar jazz solos, 26,309 tunes once the same song in different books had been removed.

§ 6

Controlling randomness

0.8

0.1 – 2.0

Temperature

Divides the logits before the softmax. Below 1.0 the model plays it safe. Above 1.0 it takes chances, and past about 1.3 it starts talking rubbish.

50

0 – 500

Top-K

Keeps the k most likely tokens and bins the rest, so nothing gets sampled from the long tail of nonsense.

0.95

0.01 – 1.0

Top-P (nucleus)

Keeps adding tokens until their probabilities add up to p. Fewer candidates when the model is sure of itself, more when it is not.

§ 7

Measuring the music

Nats per note

How surprised the model is by music it has never seen, per note rather than per token so the number survives a change of tokeniser. Two frozen sets: 1,496 melodies held out of every model since op. 11, and 92 clips rated good by ear, held out since op. 12. Lower is better, and the held-out part is the whole point. The validation loss the early models were judged on was measuring near-duplicates of the training songs and said the opposite of the truth.

N-gram repetition

Measured at 2, 4, 8 and 16-note lengths over what the model writes. High means it is stuck in a loop. The real corpus sits around 0.54 at four notes.

Pitch distribution

A histogram against the training data. Catches a model that has collapsed onto a few notes or wandered out of range.

The dials

Since op. 12: set one dial low, then high, with the rest unset, generate eight clips each way and measure the thing the dial is named for. A control that does not move the measurement is not a control.

Blind listening

Blind pairs, one model against another, same decoder, and a person picks. It is slow and it is one person’s taste, but none of the numbers above can hear, and that showed. The screen metrics the corpus used to be filtered on turned out to be a coin toss at telling good clips from bad ones.

§ 8

The studies

Twelve models in a row, each changing one or two things from the one before.

Op. 1

Baseline LSTM

LSTM [256, 512, 256] · float input · TF/Keras

The first go. Pitch in as a float, no embedding layer. Vaguely musical, no real phrasing. Lost since, but it showed the idea had legs.

Op. 2

Genre-specific data

LSTM [256, 512, 256] · float input · TF/Keras

Trained on 24 R&B/hip-hop tracks. Vocabulary of 59 tokens.

Op. 3

More data

LSTM [256, 512, 256] · float input · TF/Keras

Around 200 dance tracks, vocabulary 635. More variety, but it looped, because pitch strings could not keep up with the harmony.

Op. 4

Jazz

LSTM [256, 512, 256] · float input · TF/Keras

Around 120 jazz tracks pushed the vocabulary to 1,279. Every chord voicing was its own token and that was clearly the bottleneck.

Op. 5

Wider, mixed-genre

LSTM [512, 512, 512] · float input · TF/Keras

All 275 tracks together, wider hidden layers. Passable, but pitch strings had hit their ceiling.

Op. 6

PyTorch, embeddings, REMI

LSTM [512, 512, 512] · embed 128 · REMI · PyTorch

Rewritten in PyTorch with learned embeddings and REMI tokens. The vocabulary fell from 629 to 362 while carrying strictly more, and the output got a lot better. The way in had been the problem all along.

Op. 7

The Transformer

Transformer 8L/8H/512d · REMI + BPE 512

RoPE, SwiGLU, RMSNorm, weight tying; BPE over REMI; sequence length 256. Early-stopped at epoch 45, best validation loss 0.0952.

Op. 8

Bigger vocabulary, bigger data

Transformer 8L/8H/512d · REMI + BPE 1024

Same model, BPE doubled to 1,024, MAESTRO added. Ran all 100 epochs without early stopping, which was the first sign there was finally enough data to keep learning from.

Op. 9

True melodies, honest split, style conditioning

Transformer 8L/8H/512d · ctx 1024 · REMI + BPE 2048 + style tokens

Trained on 18,758 single-line melodies across nine styles, with a proper file-level split and a style token on the front of every training window. Best validation loss 1.33 at epoch 7 before it started overfitting. The first model where the genre dropdown did anything at all.

Op. 10

The scaling measurement

Transformer 8L/8H/512d · ctx 1024 · REMI + BPE 2048 + style tokens

Same model on 30,007 melodies, 1.6 times the ninth corpus. Best validation loss 1.30 at epoch 5, which read at the time as "more data buys little at this size". Wrong, as op. 11 showed. The split was leaking near-duplicates and the step was too small to measure a slope with. Op. 10 did show that the looping was mostly the decoder, see the Journal for the sweep.

Op. 11

Scale and clean

Transformer 10L/12H/768d · ctx 1024 · REMI + BPE 2048 + style tokens

96 million parameters on 91,373 melodies after de-duplication, four epochs. 2.710 nats per note on the frozen 1,500-piece set, against op. 10’s 3.521. Its decoder penalises the previous pitch rather than the previous token, picked by blind listening. The genre token moved the numbers. Nobody could hear the genres.

Op. 12

The rebirth: attributes you can hear

Transformer 10L/12H/768d · ctx 1024 · REMI + BPE 2048 + 43 attribute tokens

Picks up from op. 11’s weights on a rebuilt corpus of 117,682 melodies, 26,309 of them folk and jazz tunes, three passes at the full learning rate. Genre is gone. In its place, six things measured from each training melody and written on the front: key, mode, register, motion, density and repetition. 2.662 nats per note on the frozen set, and every dial moves the music the way it says, on the measurements and by ear.

§ 9

Findings

01

How the music goes in mattered more than the size of the model

Op. 5 to op. 6 changed the framework, the input and the tokeniser all at once, but the tokeniser was the bit that counted. The vocabulary fell from 629 to 362 while carrying strictly more, and the output jumped. Same as in language models. At this size, representation beat scale.

02

Widening the LSTM bought little

Op. 5’s wider layers helped a bit. The real limits were pitch strings and the recurrent bottleneck, and attention took the bottleneck away in op. 7 by letting any two positions talk directly.

03

BPE bought context almost for free

A 256-token BPE window covers two to three times the music raw REMI does, for next to nothing. Op. 8 doubled the vocabulary to soak up the busier patterns in MAESTRO.

04

Transposition was needed at this scale

Shifting every melody up to six semitones either way roughly tripled the data and loses nothing musically. Without it the models overfit in a few epochs.

05

The loops were mostly in the decoder

Opp. 9 and 10 with plain nucleus sampling collapse into the same few figures. A repetition penalty of 1.2 near temperature 0.95 gets back sixteen to twenty-six distinct pitches a phrase and repetition at or below the real corpus. Then op. 11 showed the penalty was on the wrong thing: BPE spells one pitch many ways, so the penalty has to be on the pitch, not the token.

06

The validation loss was lying

Op. 10’s validation split shared near-duplicate songs with the training set. On melodies no model had seen, the step from op. 9 to op. 10 was worth fifteen times what that loss said. Every model since is scored on frozen sets it never trained on, and data turned out to be worth about 0.17 nats per note per doubling, with a bigger model worth more again.

07

A genre word moves the numbers and not the ear

A single style token on the front of every window is enough to shift the distribution, and the release gate could see it. Nobody could hear it. A bare melody line carries very little genre, which lives in the chords, the groove and the instrument. Op. 12 replaced it with six dials you can measure, and can hear.

08

The screen cannot hear either

200 training clips were rated by ear. The numbers the corpus had been filtered on (range, pitch classes, in-key share, repetition) were a coin toss at telling the good clips from the bad ones, and the planned repetition cut would have deleted six good tunes and no bad ones. The only thing that leaned the right way was density. So op. 12 has no statistical quality filter at all.

09

Keep the old weights, use the full learning rate, stop at one cycle

For op. 12, starting from op. 11’s weights at the full pretraining rate beat starting over by 0.05 nats per note after six passes, and beat a gentle rate by 0.03. A second cycle, halved dropout and a pass on the folk tunes alone all came in worse. More passes of any kind just memorise.

§ 10

Limitations, and what comes next

One line at a time

The models write a single melodic line. Melody, bass, chords and drums together would need interleaved token streams or a different architecture altogether.

Bigger is next

Data and model size both kept paying off right up to op. 12, and this corpus is tapped out at 96M. The next real gain needs a bigger model or a lot more melodies, which is op. 13.

Chords and tempo are waiting

Key arrived with op. 12 as one of the six dials. Chords and tempo follow the same prefix trick and are the next study, op. 12.5. The chord pilot already showed they are worth about 6% on their own, once the tokeniser is learned on melody first.

The ear test is slow

A human ear is the only judge here that can actually hear, and that means a couple of hundred clips a week at best. A learned critic trained on those ratings is open work.

Positions are tokens, not beats

RoPE knows where a token sits in the sequence, not where it sits in the bar. A music-aware position encoding might help the phrasing.

Nobody can say what they thought

The songbook keeps the compositions but not anyone’s opinion of them. Ratings on the songbook would give op. 13 something to learn taste from.

§ 11

Bibliography

[1]

Huang, C-Z. A., Vaswani, A., Uszkoreit, J., Shazeer, N., Simon, I., Hawthorne, C., Dai, A., Hoffman, M., Dinculescu, M., Eck, D. (2019). Music Transformer: Generating Music with Long-Term Structure. arXiv

[2]

Huang, Y-S., Yang, Y-H. (2020). Pop Music Transformer: Beat-based Modeling and Generation of Expressive Pop Piano Compositions. arXiv

[3]

Fradet, N., Gutowski, N., et al. (2023). Byte Pair Encoding for Symbolic Music. arXiv

[4]

Hawthorne, C., Stasyuk, A., Roberts, A., Simon, I., Huang, C-Z. A., Dieleman, S., Elsen, E., Engel, J., Eck, D. (2019). Enabling Factorized Piano Music Modeling and Generation with the MAESTRO Dataset. arXiv

[5]

Su, J., Lu, Y., Pan, S., Murtadha, A., Wen, B., Liu, Y. (2021). RoFormer: Enhanced Transformer with Rotary Position Embedding. arXiv

[6]

Shazeer, N. (2020). GLU Variants Improve Transformer. arXiv

[7]

Zhang, B., Sennrich, R. (2019). Root Mean Square Layer Normalization. arXiv

[8]

Press, O., Wolf, L. (2017). Using the Output Embedding to Improve Language Models. arXiv

[9]

Sennrich, R., Haddow, B., Birch, A. (2016). Neural Machine Translation of Rare Words with Subword Units. arXiv

[10]

Loshchilov, I., Hutter, F. (2016). SGDR: Stochastic Gradient Descent with Warm Restarts. arXiv

§ 12

The data

The Melograph is a research project. It is free to use, and it exists to test what a melody model can learn and how to measure it.

The training data is public research corpora: the Lakh MIDI collection, POP909, Wikifonia lead sheets, MAESTRO, the Nottingham and Essen folk collections, the Weimar jazz solos and the Meertens Dutch song collection. Every licence was read before a collection went in. Meertens is non-commercial, and the project respects that. The Session was left out because its terms forbid exactly this use.

Lakh is MIDI arrangements that people made and shared over the years, mostly of existing songs. What the model sees is a single line of note pitches and durations lifted from the top of each file. No audio, no recordings, no lyrics, no artist or song names. It has never heard anyone.

What comes out is a melody of a few hundred notes played by a synth. Training stops before the model starts repeating its data, and near-duplicate songs were removed so nothing is over-represented. It can still write a line that sounds like something, the way anyone who has heard a lot of pop can.

Wrote or arranged something in one of those collections and want it out? Email themelograph@niall.one and it leaves the next training run.

That's the method.

Go and write something nobody has heard.

Compose a melody →