Design a reproducible symbolic melody experiment with a narrow objective, traceable MIDI data, leakage-resistant splits, simple baselines, controlled model comparisons, and clear success and stopping criteria.
About 16 minutes
Guiding question
What makes a music-generation experiment small enough to understand?
By the end, you’ll be able to
Turn a broad music-generation idea into a narrow and testable hypothesis.
Explain why symbolic MIDI data is often practical for a first generative experiment.
Define a consistent event representation, vocabulary, sequence length, and generation task.
Create training, validation, and test splits that reduce composer, song, and arrangement leakage.
Compare a simple statistical baseline with small recurrent and Transformer models.
Select training, validation, musical, computational, and qualitative success criteria.
Control randomness, configuration, and checkpoints so an experiment can be reproduced.
Use pilot results to decide whether to stop, revise, scale, or change the model strategy.
Training a small model is most useful when the experiment answers one clear question.
Can a small Transformer generate convincing music? is too broad. It leaves the representation, dataset, model size, musical domain, output length, comparison method, and meaning of convincing undefined.
A more useful question is:
Does a two-layer Transformer predict the next event in sixteen-bar monophonic melodies better than a first-order Markov baseline when both use the same training data and tokenisation?
That question is narrow enough to implement, compare, diagnose, and repeat.
Begin with one model behaviour
Choose one output and one task.
A manageable first task might be:
Continue a monophonic melody
Predict the next symbolic event
Generate an eight-bar melody from a start token
Harmonise a supplied melody using chord labels
Fill a masked symbolic bar
Do not begin by combining text, lyrics, full instrumentation, expressive audio, long-form structure, and production quality. Every added capability introduces another representation, dataset, loss, failure mode, and evaluation problem.
MIDI represents performance instructions and musical events rather than a recorded waveform. A symbolic model can work with pitch, onset, duration, velocity, program, tempo, control changes, and pedal events without learning microphones, rooms, mastering, codecs, or waveform reconstruction.
This reduces the output space and makes errors easier to inspect. A wrong pitch, invalid duration, repeated note, or missing stop token can be identified directly.
The compromise is that MIDI does not capture the complete sound of a recording. The final audio depends on the synthesiser or instrument used for playback.
A first symbolic experiment versus audio generation
Swipe sideways to view the full comparison
Area
Symbolic MIDI experiment
High-fidelity audio experiment
Target
Notes and musical events
Waveform, spectrogram, codec tokens, or audio latents
Sequence size
Usually tied to musical activity
Often many values or tokens per second
Playback
Requires a synthesiser
Directly reconstructs or produces audio
Debugging
Events can be inspected as notation or tables
Many failures require listening and spectral analysis
Compute
Can support small CPU or single-GPU prototypes
Usually requires substantially more memory and compute
Acoustic realism
Not learned by the generator
A central part of the task
Choose a dataset that matches the question
A dataset is suitable only when its content, permissions, representation, and grouping information support the experiment.
For a first model, prioritise:
Clear rights and permitted use
Consistent symbolic files
A narrow musical domain
Enough complete pieces or phrases for held-out evaluation
Stable performer, composer, work, or source identifiers
Documentation of preprocessing and exclusions
A larger dataset is not automatically better if its files are duplicated, weakly documented, or unrelated to the target task.
Examples in practice
Real-world dataset: MAESTRO
MAESTRO contains roughly 200 hours of aligned audio and MIDI from International Piano-e-Competition performances. Its MIDI includes expressive key velocities and pedal information. The official dataset page provides predefined train, validation, and test splits and releases the dataset under CC BY-NC-SA 4.0, so it is useful for research and educational experiments but requires careful attention to its non-commercial condition.
Real-world dataset: Lakh MIDI
The Lakh MIDI Dataset contains 176,581 unique MIDI files, including 45,129 matched and aligned to entries in the Million Song Dataset. Its scale makes it valuable for symbolic research, but a small beginner experiment should not assume that every file has uniform quality, simple structure, or identical usage status.
Possible dataset choices
Swipe sideways to view the full comparison
Dataset source
Benefit
Main caution
Recommended role
Project-owned melodies
Clear scope and controllable provenance
May be too small or stylistically narrow
Best default for a first demonstrator
Explicitly licensed public collection
Can support publication and reuse
Licence terms may differ across files
Good after a file-level rights audit
MAESTRO
High-quality expressive piano MIDI with documented splits
Piano performance task and non-commercial licence condition
Research comparison or educational prototype
Lakh MIDI
Large and musically varied
Complex cleaning, grouping, duplication, and rights questions
Later data-engineering experiment
Random MIDI files from the web
Easy to collect
Unknown provenance, quality, duplication, and permissions
Do not use as the default dataset
Audit the symbolic data before modelling
1
Parse every file
Record which files load successfully and quarantine malformed files.
2
Inspect tracks and instruments
Decide whether the experiment is monophonic, piano-only, melody-only, or multi-track.
3
Validate note events
Check pitches, start times, end times, overlaps, velocities, and hanging notes.
4
Standardise timing
Choose whether to preserve expressive timing or quantise to a beat grid.
5
Detect duplicates and related files
Group alternate arrangements, transpositions, performances, or excerpts before splitting.
6
Record exclusions
Store the reason every rejected file or track was removed.
The same MIDI file can be represented in several ways.
A fixed-grid piano roll records active pitches at each time step. An event representation records changes such as note-on, note-off, time-shift, and velocity. A note-tuple representation might store pitch, onset, and duration together.
The representation determines vocabulary size, sequence length, timing precision, and which errors the model can make. It should be fixed before comparing model architectures.
Three symbolic representations
Swipe sideways to view the full comparison
Representation
Strength
Limitation
Good first use
Pitch-only melody tokens
Very small and easy to inspect
Loses duration, rhythm, velocity, and rests unless added separately
A basic monophonic baseline
Fixed-grid piano roll
Simple alignment with beats and bars
Long sequences and fixed timing resolution
Quantised melodies or chords
Event-based sequence
Supports expressive timing, velocity, note starts, and endings
Requires careful token grammar and sequence validation
RNN or Transformer continuation
Create a reproducible tokenisation pipeline
1
Select supported musical information
Choose pitch, duration, timing, velocity, pedal, instrument, bar, and stop information.
2
Define timing resolution
Set the beat grid or time-shift bins.
3
Define the vocabulary
List every legal token and reserve start, stop, padding, and unknown tokens where required.
4
Specify event ordering
Define how simultaneous note endings, note starts, controls, and time shifts are ordered.
5
Encode and decode
Confirm that tokens can be converted back into valid symbolic music.
6
Test round trips
Compare the original symbolic input with its decoded version before training.
7
Version the tokenizer
Changing token rules creates a different dataset and may invalidate checkpoints.
Split pieces before creating training windows
A model should be evaluated on musical material that was not used for parameter updates or repeated experiment decisions.
If one song is cut into many overlapping windows and those windows are randomly split, nearly identical phrases can appear in training and validation. Validation loss may then measure recognition of the same work rather than generalisation to new music.
Assign complete works, source files, composers, performers, or other related groups to splits before extracting windows.
Which grouping level should be used?
Swipe sideways to view the full comparison
Risk
Useful group
Reason
Overlapping excerpts
Source MIDI file
All windows from one file stay together
Different performances of one composition
Composition or work ID
The same notes do not appear across splits through another performance
Many works by one composer
Composer ID
Tests transfer to unseen composers when that is the research question
Multiple arrangements of one song
Song or composition family
Melody and harmony do not leak through alternate arrangements
Synthetic transpositions
Original source ID
Augmented versions remain with the original example
Create windows after the split
Long pieces are often divided into fixed-length token windows for batching.
A context length of 64 tokens does not necessarily equal 64 notes or a fixed number of bars. It depends on the tokenisation. A dense passage can consume more tokens than a sparse passage covering the same duration.
Record both token length and approximate musical duration so context comparisons remain interpretable.
Build a baseline before a neural model
A baseline shows whether the neural system adds value beyond a simpler procedure.
For melody generation, useful baselines include:
Sampling pitches from their training frequencies
A first-order Markov chain using the previous event
An n-gram model using a short event history
Copying or repeating the seed phrase
A complicated model that cannot beat a simple baseline on held-out prediction and musical evaluation has not justified its complexity.
A useful model ladder
Swipe sideways to view the full comparison
Model
What it tests
Main limitation
Frequency baseline
Whether the evaluation rewards basic dataset statistics
Ignores sequence order
First-order Markov model
Whether short note transitions explain the task
Very limited memory
Small RNN or LSTM
Whether a learned hidden state improves sequence modelling
Earlier information is compressed into a recurrent state
Small Transformer
Whether direct attention over the context improves prediction
Higher memory use and more design choices
Examples in practice
Real-world model: Performance RNN
Performance RNN is an LSTM-based recurrent model designed for polyphonic piano performance with expressive timing and dynamics. It uses an event-based symbolic representation, demonstrating that MIDI events can model more than a quantised melody while remaining separate from waveform generation.
Real-world model: Music Transformer
Music Transformer applies self-attention and relative positional information to symbolic music. The original work compared its approach with recurrent models and demonstrated minute-long expressive piano generation and motif-conditioned continuation. A tiny classroom Transformer should be treated as a simplified experiment, not a reproduction of the full research system.
Change one major factor at a time
When comparing an RNN and Transformer, keep the dataset, splits, tokenizer, context length, training budget, loss, generation prompts, and evaluation procedure fixed where possible.
If the Transformer receives more data, a longer context, and more optimisation steps, the experiment cannot identify which change produced the difference.
A controlled comparison may not make the systems identical, but it should document every meaningful difference.
Define success before listening to the result
A successful small experiment should meet several kinds of criteria.
Technical criteria check whether the pipeline works. Predictive criteria compare held-out loss with baselines. Musical criteria measure pitch, rhythm, repetition, and structure. Qualitative criteria use blinded human listening. Operational criteria measure training cost and generation speed.
Predefining the criteria reduces the temptation to select whichever metric happens to improve.
Evaluate the experiment at several levels
Swipe sideways to view the full comparison
Level
Example measure
What it reveals
Pipeline validity
Percentage of decodable generated sequences
Whether the representation and generator produce legal output
Prediction
Validation cross-entropy or perplexity
How well the model predicts held-out tokens
Pitch
Pitch range, interval distribution, and out-of-range rate
Whether generated melodies occupy plausible pitch space
Rhythm
Duration, rest, onset, and note-density distributions
Whether timing resembles the target data
Repetition
Repeated n-grams and repeated phrase estimates
Whether the model is random, coherent, or trapped in loops
Novelty
Exact and near-match checks against training pieces
Whether generation appears to reproduce known sequences
Human judgement
Blind ratings of coherence, interest, and musicality
Properties not captured by token metrics
Resources
Training time, peak memory, and generation latency
Whether the approach is practical
Listen without revealing the model name
Human evaluation can compare shuffled samples from the baseline, RNN, Transformer, and held-out data.
Use the same synthesiser, loudness treatment, duration, seed format, and playback interface for every model. Do not tell listeners which system produced each sample.
Ask focused questions such as rhythmic stability, melodic coherence, repetition, or preference. A single broad question such as Is this good? is difficult to interpret.
Record everything required to repeat the run
Random initialisation, data shuffling, dropout, sampling, and hardware operations can cause runs to differ.
Record:
Dataset manifest and checksums
Split group IDs
Tokenizer version
Model configuration
Optimiser and learning-rate schedule
Batch size and gradient accumulation
Random seeds
Software versions
Hardware type
Checkpoint selection rule
Generation prompts and sampling settings
PyTorch notes that complete reproducibility is not guaranteed across all releases, platforms, and devices, even when randomness is controlled.
Decide when the experiment should stop
A pilot should not run indefinitely.
Stop or revise when:
The baseline already satisfies the project need
The neural model does not beat the baseline
Training loss falls while validation worsens
Generated syntax remains invalid
The representation removes the musical property being studied
Run the selected configurations across several seeds when resources permit.
9
Make a decision
Stop, revise the representation, improve the data, or scale the model based on predefined evidence.
Interactive lesson
Design a Tiny Melody Model
Try it: Begin with the recommended project-owned MIDI preset. Define one hypothesis, inspect the data audit, select a representation, and split complete works before extracting windows. Train the baseline simulation first, then compare the RNN and Transformer under the same budget. The experiment is complete only after you define a decision rule.
A useful first music experiment defines one narrow objective, uses traceable symbolic data, fixes the tokenisation, splits complete musical groups before creating sequence windows, compares simple baselines with small neural models, and sets success and stopping criteria before training.
When improvement becomes memorisation
A small experiment can produce falling training loss and attractive samples while learning the dataset too literally.
The next section, Overfitting and Memorisation, examines training-validation gaps, duplicate data, exact and approximate reproduction, model capacity, and the difference between learning a musical pattern and recalling a training example.
Check your understanding
Ready for a quick check?
Test whether you can define a narrow symbolic-music experiment, prevent split leakage, select baselines, and establish reproducible success criteria.
Ready to continue?
Save this section to your account and continue from any device.