Ismail Ben Alla

MusicGen

Transformer vs LSTM vs RNN for Music

Generative AI · May 2024 · Completed

Three neural networks compete to write folk-style tunes from text notation.

Built withPyTorchKerasStreamlitmusic21FluidSynth + pydubPoetry

MusicGen — overview

Overview

I wanted a controlled comparison of the three classic sequence models (Transformer, LSTM, and RNN) on the same music data, rather than one heavily tuned model and a guess about why it worked.

MusicGen represents songs as ABC notation, a text format for sheet music, and trains each architecture to continue that text one token at a time. I implemented the Transformer, LSTM, and RNN from scratch in PyTorch; the LSTM and RNN also have versions built on PyTorch's own layers. I added three tokenizers (a character-level one, a byte-pair-encoding tokenizer I trained myself, and a Keras word tokenizer) so I could see how tokenization changes the results.

A Streamlit app ties it together. You pick a model, give it a few opening notes, and it generates tunes that are rendered to audio and can be downloaded as MP3.

The question

On the same music corpus, how do Transformer, LSTM, and RNN compare for symbolic music generation?

Key features

How it works

  1. Songs as text

    Each tune's ABC notation is wrapped in start and end tokens, and the tunes are joined into one long training text.

  2. Tokenize

    The text is split into tokens by one of three tokenizers: individual characters, merges learned with byte-pair encoding, or Keras word tokens.

  3. Train next-token predictors

    A decoder-only Transformer, an LSTM, and an RNN each learn to predict the next token, while training and validation loss and accuracy are tracked.

  4. Sample new music

    From the user's opening notes, the model samples tokens one at a time, controlled by temperature and top-k.

  5. Render to audio

    The generated ABC is parsed with music21, written to MIDI, synthesized to WAV with FluidSynth, and converted to MP3 for playback and download.

Examples

The Streamlit app: starting ABC notes and sampling settings on the left, and generated tunes with players and MP3 download links on the right.
The Streamlit app: starting ABC notes and sampling settings on the left, and generated tunes with players and MP3 download links on the right.
Transformer: training and validation loss and accuracy per epoch.
Transformer: training and validation loss and accuracy per epoch.
LSTM: training and validation loss and accuracy per epoch.
LSTM: training and validation loss and accuracy per epoch.
RNN: training and validation loss and accuracy per epoch.
RNN: training and validation loss and accuracy per epoch.

Tech stack

What I learned

Limitations