Overview

14 Building and Training a Music Transformer

This chapter reframes AI music creation as a sequence modeling problem and walks through building a GPT-style Transformer that composes piano music from performance data. Starting with MIDI performances, music is represented as a stream of discrete events rather than multi-track grids, enabling the use of text-generation techniques to predict the next event in context. The workflow runs end to end: convert MIDI to events, map events to indexes, train a decoder-only Transformer on long sequences to capture musical dependencies, generate new event sequences conditioned on a short prompt, and finally convert the result back to a playable MIDI file.

A performance-based representation underpins the approach, with four event types—note_on, note_off, time_shift, and velocity—capturing pitch, note duration, rhythmic spacing, and dynamics. Time is discretized in 0.01-second increments (binned values), and velocities are quantized into 32 bins to keep the vocabulary compact and training tractable. All unique events form a vocabulary of 388 tokens, augmented by special end-of-sequence and padding tokens for a total of 390. Training data are built from the MAESTRO piano dataset by tokenizing each piece, mapping tokens to indexes, segmenting into sequences of length 2048, and forming input-output pairs via a one-step right shift to teach next-event prediction.

The model is a decoder-only Transformer with six layers, 512-dimensional embeddings, and eight attention heads, using learned positional embeddings and totaling about 20.16 million parameters. It is trained with Adam and cross-entropy loss (ignoring padding), with gradient clipping for stability, on small batches of long sequences to capture long-range musical structure. For generation, a short prompt (e.g., the first few hundred events) seeds autoregressive sampling; temperature scaling controls creativity and diversity in the output. The system produces coherent, stylistically consistent piano music and illustrates how GPT-style Transformers can be adapted from text to performance-driven music generation.

The architecture of a music Transformer. Music files in MIDI formats are first converted into sequences of musical events. These events are then tokenized and converted into indexes. We organize these indexes into sequences of 2048 elements, and each batch contains 2 such sequences. The input sequence first undergoes word embedding and positional encoding, with the input embedding being the sum of these two components. This input embedding is then processed through six decoder layers, each utilizing self-attention mechanisms to capture the relationships among different musical events in the sequence. After passing through the decoder layers, the output undergoes layer normalization to ensure stability in the training process. It then passes through a linear layer, resulting in an output size of 390, which corresponds to the number of unique tokens in the vocabulary. This final output represents the predicted logits for the next musical event in the sequence.
The training process for a music Transformer to generate music.

Summary

  • The performance-based representation of music enables us to represent a musical piece as a sequence of notes, which include control messages and velocity values. These notes can be further reduced to four kinds of musical events: note-on, note-off, time-shift, and velocity. Each event type can assume various values. Consequently, we can transform a music piece into a sequence of tokens and then into indexes.
  • A music Transformer adapts the Transformer architecture, originally designed for natural language processing (NLP) tasks, for music generation. This model is designed to generate sequences of musical notes by learning from a large dataset of existing music. It is trained to predict the next note in a sequence based on previous notes, by recognizing patterns, structures, and relationships among various musical elements in the training data.
  • Just as in text generation, we can use temperature to regulate the creativity of the generated music.

FAQ

What is a music Transformer and why is a decoder-only architecture used here?The music Transformer is a GPT-style, decoder-only Transformer that models a piece of music as a sequence of discrete event tokens and predicts the next event given all previous ones. Unlike translation, music generation doesn’t need an encoder for a separate source sequence, so a causal, decoder-only stack with self-attention is sufficient and efficient.
How is music represented before tokenization?Music is represented in a performance-based manner using MIDI-like control messages: note_on (start a pitch), note_off (stop a pitch), time_shift (elapsed time), and velocity (playing intensity). This captures both the structure and expressiveness needed for generation.
How are time and velocity discretized to control vocabulary size?- Time is quantized into 0.01-second increments and bucketed into 100 values (0–99), where 0 = 0.01s, 99 = 1.00s; longer gaps are represented by multiple time_shift tokens.
- Velocity (0–127) is binned into 32 buckets (0–31). Separating velocity from note_on drastically reduces the number of unique event types.
What are the token types, their value ranges, and index ranges?- note_on: values 0–127 → indexes 0–127
- note_off: values 0–127 → indexes 128–255 (128 + value)
- time_shift: values 0–99 → indexes 256–355 (256 + value)
- velocity: values 0–31 → indexes 356–387 (356 + value)
Special tokens: EOS = 388 (end of sequence for y), PAD = 389 (padding). Total vocabulary size = 390.
Why is the maximum sequence length set to 2048 tokens?Music often contains long-range dependencies. A context window of 2048 tokens lets the model capture long-term relations (e.g., motifs, phrasing, pedal/sustain patterns) while remaining trainable on a single GPU with small batch sizes.
What dataset is used and how is it prepared?The MAESTRO v2.0.0 piano dataset is used. MIDI files are split into train/validation/test per the provided JSON metadata. Each MIDI is converted to events with processor.py, mapped to indexes, then packed into 2048-length input (x) and target (y) sequences, padding with 389 as needed and marking EOS with 388 for y when sequences are short.
What are the key hyperparameters and model size?- Layers: 6 decoder blocks
- Heads: 8 attention heads (64 dims each for 512 embedding)
- Embedding: 512 (learned token and learned positional embeddings)
- Vocab size: 390
- Block size: 2048
- Dropout: 0.1 (embedding, attention, residual)
Parameter count: approximately 20.16 million.
How is the model trained?- Objective: next-token prediction with cross-entropy over 390 classes
- Data: (x, y) where y is x shifted right by 1
- Loss: CrossEntropyLoss(ignore_index=389) to exclude PAD
- Optimizer: Adam (lr=1e-4), gradient norm clipping at 1.0
- Epochs: 100 (example run ~3 hours on a CUDA GPU)
How does music generation work after training?Provide a prompt (e.g., first ~250 tokens) and iteratively sample the next token from softmax probabilities over logits, optionally scaled by temperature, until a target length is reached (e.g., 1000 tokens). The generated index sequence is then decoded back to a playable MIDI file.
What does the temperature parameter do, and do we need top-k?Temperature rescales logits before softmax. Lower values (e.g., 0.7) make outputs more conservative and predictable; higher values (e.g., 1.5) increase diversity and risk-taking. The chapter uses temperature alone for simplicity, but you can add top-k or nucleus sampling to further control variety.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Learn Generative AI with PyTorch ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Learn Generative AI with PyTorch ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Learn Generative AI with PyTorch ebook for free