Lunar Boom Learning

4.3 · Designing a Small Experiment

Section 4.3 of 4.6

Designing a Small Experiment

A manageable path into music model building

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:

    1. Continue a monophonic melody
    2. Predict the next symbolic event
    3. Generate an eight-bar melody from a start token
    4. Harmonise a supplied melody using chord labels
    5. 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.

Turn a broad project into a testable experiment

Swipe sideways to view the full comparison

DecisionBroad versionSmall experimental version
Musical domainAll musicMonophonic melodies in one documented collection
OutputFinished songsEight or sixteen bars of symbolic melody
RepresentationRaw audioPitch, duration, time-shift, and stop events
ModelsFrontier generatorMarkov baseline, small RNN, and small Transformer
ConditioningText, chords, lyrics, and referencesStart token or short melody prefix
SuccessSounds goodLower held-out loss, valid syntax, controlled repetition, and favourable blind listening

Why start with symbolic music?

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

AreaSymbolic MIDI experimentHigh-fidelity audio experiment
TargetNotes and musical eventsWaveform, spectrogram, codec tokens, or audio latents
Sequence sizeUsually tied to musical activityOften many values or tokens per second
PlaybackRequires a synthesiserDirectly reconstructs or produces audio
DebuggingEvents can be inspected as notation or tablesMany failures require listening and spectral analysis
ComputeCan support small CPU or single-GPU prototypesUsually requires substantially more memory and compute
Acoustic realismNot learned by the generatorA 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:

    1. Clear rights and permitted use
    2. Consistent symbolic files
    3. A narrow musical domain
    4. Enough complete pieces or phrases for held-out evaluation
    5. Stable performer, composer, work, or source identifiers
    6. 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 sourceBenefitMain cautionRecommended role
Project-owned melodiesClear scope and controllable provenanceMay be too small or stylistically narrowBest default for a first demonstrator
Explicitly licensed public collectionCan support publication and reuseLicence terms may differ across filesGood after a file-level rights audit
MAESTROHigh-quality expressive piano MIDI with documented splitsPiano performance task and non-commercial licence conditionResearch comparison or educational prototype
Lakh MIDILarge and musically variedComplex cleaning, grouping, duplication, and rights questionsLater data-engineering experiment
Random MIDI files from the webEasy to collectUnknown provenance, quality, duplication, and permissionsDo 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.

  7. Produce summary statistics

    Measure piece lengths, pitch ranges, event counts, keys, metres, tempos, and source concentration.

Decide what one token means

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

RepresentationStrengthLimitationGood first use
Pitch-only melody tokensVery small and easy to inspectLoses duration, rhythm, velocity, and rests unless added separatelyA basic monophonic baseline
Fixed-grid piano rollSimple alignment with beats and barsLong sequences and fixed timing resolutionQuantised melodies or chords
Event-based sequenceSupports expressive timing, velocity, note starts, and endingsRequires careful token grammar and sequence validationRNN 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

RiskUseful groupReason
Overlapping excerptsSource MIDI fileAll windows from one file stay together
Different performances of one compositionComposition or work IDThe same notes do not appear across splits through another performance
Many works by one composerComposer IDTests transfer to unseen composers when that is the research question
Multiple arrangements of one songSong or composition familyMelody and harmony do not leak through alternate arrangements
Synthetic transpositionsOriginal source IDAugmented 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:

    1. Sampling pitches from their training frequencies
    2. A first-order Markov chain using the previous event
    3. An n-gram model using a short event history
    4. 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

ModelWhat it testsMain limitation
Frequency baselineWhether the evaluation rewards basic dataset statisticsIgnores sequence order
First-order Markov modelWhether short note transitions explain the taskVery limited memory
Small RNN or LSTMWhether a learned hidden state improves sequence modellingEarlier information is compressed into a recurrent state
Small TransformerWhether direct attention over the context improves predictionHigher 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

LevelExample measureWhat it reveals
Pipeline validityPercentage of decodable generated sequencesWhether the representation and generator produce legal output
PredictionValidation cross-entropy or perplexityHow well the model predicts held-out tokens
PitchPitch range, interval distribution, and out-of-range rateWhether generated melodies occupy plausible pitch space
RhythmDuration, rest, onset, and note-density distributionsWhether timing resembles the target data
RepetitionRepeated n-grams and repeated phrase estimatesWhether the model is random, coherent, or trapped in loops
NoveltyExact and near-match checks against training piecesWhether generation appears to reproduce known sequences
Human judgementBlind ratings of coherence, interest, and musicalityProperties not captured by token metrics
ResourcesTraining time, peak memory, and generation latencyWhether 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:

    1. Dataset manifest and checksums
    2. Split group IDs
    3. Tokenizer version
    4. Model configuration
    5. Optimiser and learning-rate schedule
    6. Batch size and gradient accumulation
    7. Random seeds
    8. Software versions
    9. Hardware type
    10. Checkpoint selection rule
    11. 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:

    1. The baseline already satisfies the project need
    2. The neural model does not beat the baseline
    3. Training loss falls while validation worsens
    4. Generated syntax remains invalid
    5. The representation removes the musical property being studied
    6. Results vary too strongly across seeds
    7. Data leakage is discovered
    8. Rights or provenance cannot be resolved
    9. Compute cost exceeds the planned budget

A negative result can still be useful when it removes an unsupported direction.

A complete small melody experiment

  1. State the question

    Compare whether a small Transformer improves held-out next-event prediction over Markov and RNN baselines.

  2. Select traceable data

    Use project-owned or explicitly licensed monophonic MIDI files with stable source and composition identifiers.

  3. Freeze the representation

    Use one event vocabulary containing pitch, duration or time-shift, rests, start, stop, and padding.

  4. Group and split complete works

    Assign related files to training, validation, and test before producing sequence windows.

  5. Build simple baselines

    Implement frequency, Markov, and phrase-copy baselines.

  6. Train small neural models

    Use a compact RNN and Transformer under recorded and comparable budgets.

  7. Evaluate predictions and generations

    Measure loss, syntax, musical distributions, repetition, novelty, resource use, and blind listening.

  8. Repeat the final comparison

    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.

Checking your account…
Sources for this lesson (10)
  1. Reproducibility — PyTorch contributors
  2. Cross-Validation: Evaluating Estimator Performance — scikit-learn contributors
  3. GroupShuffleSplit — scikit-learn contributors
  4. GroupKFold — scikit-learn contributors
  5. pretty_midi Documentation — Colin Raffel and contributors
  6. The MAESTRO Dataset — Curtis Hawthorne et al.
  7. The Lakh MIDI Dataset v0.1 — Colin Raffel
  8. Performance RNN: Generating Music with Expressive Timing and Dynamics — Ian Simon and Sageev Oore (2017)
  9. Music Transformer — Cheng-Zhi Anna Huang et al. (2018)
  10. Music Transformer: Generating Music with Long-Term Structure — Google Magenta (2018)
Browse all contextual sources →