MidiBERT for Music Understanding
1. What is MidiBERT?
What is MidiBERT?
MidiBERT is a transformer-based model specifically designed for symbolic music understanding, leveraging the success of BERT (Bidirectional Encoder Representations from Transformers) in natural language processing. Unlike traditional approaches that process raw audio waveforms, MidiBERT operates on symbolic music representations, such as MIDI files, which encode musical events like note pitches, durations, velocities, and timing. This allows the model to capture high-level musical structures, including harmony, rhythm, and melody, in a computationally efficient manner.
Architecture and Tokenization
MidiBERT employs a transformer encoder architecture, similar to BERT, but adapts the tokenization process to musical data. Instead of word or subword tokens, MidiBERT tokenizes MIDI events into discrete units representing musical elements. Each token corresponds to a specific musical event, such as:
- Note On/Off: Indicates the start or end of a note with associated pitch and velocity.
- Time Shift: Represents the temporal gap between consecutive events.
- Velocity Change: Captures dynamics variations in the performance.
The tokenization process converts a MIDI sequence into a series of discrete tokens, which are then embedded into a continuous vector space. These embeddings are fed into the transformer encoder, which learns contextual relationships between musical events through self-attention mechanisms.
Pre-training Objectives
MidiBERT is pre-trained using two primary objectives adapted from BERT:
- Masked Language Modeling (MLM): Randomly masks a subset of tokens in the input sequence and trains the model to predict the masked tokens based on their context. This encourages the model to learn bidirectional representations of musical structure.
- Next Sentence Prediction (NSP): Modified to predict whether two musical segments are contiguous or non-contiguous, fostering an understanding of longer-term musical coherence.
where M represents the set of masked tokens, and x denotes the input sequence.
Applications and Advantages
MidiBERT excels in tasks requiring deep musical understanding, such as:
- Music Generation: Conditionally generating coherent musical sequences by leveraging learned representations.
- Music Classification: Identifying genres, styles, or emotions from symbolic music data.
- Music Transcription: Converting performances into symbolic notation with high accuracy.
Its symbolic approach offers advantages over waveform-based models, including reduced computational complexity and explicit modeling of musical semantics. However, it relies on the availability of high-quality symbolic data, which may limit its applicability in scenarios where only audio recordings are available.

Key Applications of MidiBERT in Music Analysis
MidiBERT, a transformer-based model pre-trained on symbolic music data (MIDI), excels in capturing hierarchical and long-range dependencies in musical sequences. Its architecture, inspired by BERT, enables it to process polyphonic music with nuanced understanding. Below are its key applications in advanced music analysis.
Music Generation and Composition
MidiBERT's bidirectional attention mechanism allows it to generate coherent musical sequences by predicting masked tokens in a given context. The model learns latent representations of musical structure, enabling it to compose melodies, harmonies, and even full arrangements. For conditional generation, the probability distribution for the next token yt given previous tokens y<t is computed as:
where W and b are learnable parameters, and ht is the hidden state at position t.
Automatic Music Transcription
MidiBERT can transcribe polyphonic audio into symbolic notation by first converting audio to a piano roll representation, then predicting note onsets, durations, and velocities. The model's self-attention layers help disambiguate overlapping notes, a common challenge in transcription. Performance is measured using the F1-score for note-level accuracy:
Music Style Transfer
By fine-tuning MidiBERT on genre-specific datasets, the model can transform a musical piece from one style to another (e.g., classical to jazz). The key lies in its ability to isolate style-agnostic features (e.g., melody) from style-specific ones (e.g., rhythm patterns). Cross-attention mechanisms facilitate this disentanglement.
Emotion and Structure Analysis
MidiBERT's embeddings correlate with perceptual features like emotion (valence/arousal) and formal structure (e.g., verse-chorus segmentation). A linear probe trained on its embeddings achieves state-of-the-art performance in emotion classification, leveraging the attention weights to identify emotionally salient segments.
Real-Time Performance Assistance
In live performances, MidiBERT can predict upcoming notes or harmonies based on the performer's input, acting as an AI collaborator. The model's low-latency inference is achieved through optimized attention caching, reducing the computational complexity of autoregressive generation from O(n2) to O(n) for sequential decoding.
1.3 Advantages of Using Transformer Models for Music
Long-Range Dependency Modeling
Traditional recurrent neural networks (RNNs) and convolutional neural networks (CNNs) struggle with capturing long-range dependencies in sequential data due to their inherent architectural limitations. RNNs suffer from vanishing gradients, while CNNs are constrained by their fixed receptive fields. Transformer models, however, leverage self-attention mechanisms to compute pairwise relationships between all tokens in a sequence, regardless of their positional distance. For musical sequences, this enables the model to recognize harmonic progressions, melodic motifs, and rhythmic patterns that span hundreds of time steps.
Here, Q, K, and V represent the query, key, and value matrices, respectively, while dk is the dimension of the key vectors. The softmax operation ensures that the attention weights sum to one, allowing the model to focus on the most relevant parts of the input sequence.
Parallelization and Scalability
Unlike RNNs, which process sequences sequentially, Transformers process all tokens in parallel during both training and inference. This parallelization drastically reduces training time and enables efficient scaling to large datasets. For music applications, where sequences can be extremely long (e.g., MIDI files with thousands of time steps), this property is particularly advantageous. The computational complexity of self-attention is O(n2) for sequence length n, but techniques like sparse attention or memory-efficient variants mitigate this cost.
Hierarchical Feature Learning
Transformers inherently learn hierarchical representations through their multi-head attention mechanism and deep stack of layers. In music, lower layers may capture local features like note durations and intervals, while higher layers model global structures such as chord progressions and song form. This hierarchical abstraction aligns well with the multi-scale nature of musical compositions, where local motifs contribute to larger-scale themes.
Transfer Learning and Pretraining
Transformer architectures like MidiBERT benefit from pretraining on large-scale musical corpora, learning generalizable representations that can be fine-tuned for specific downstream tasks (e.g., melody generation, style transfer, or music classification). The masked language modeling (MLM) objective, where random tokens are masked and predicted, forces the model to develop a robust understanding of musical context. This approach mirrors successful NLP models like BERT, demonstrating the Transformer's versatility across domains.
Handling Polyphonic Music
Music is inherently polyphonic, with multiple notes sounding simultaneously. Transformers excel at modeling such complex interactions due to their ability to attend to multiple input tokens simultaneously. By representing musical events as discrete tokens (e.g., note-on, note-off, velocity), the model can learn intricate dependencies between concurrent and sequential musical events, capturing the rich texture of polyphonic compositions.
Flexible Input Representations
Transformers can accommodate various musical representations, including MIDI events, piano rolls, or symbolic notation. The tokenization process can be adapted to preserve musical semantics, such as pitch, duration, and dynamics. This flexibility allows the same architecture to be applied across different musical tasks without significant structural modifications.
2. Transformer-Based Architecture Overview
Transformer-Based Architecture Overview
The foundation of MidiBERT lies in the transformer architecture, originally introduced by Vaswani et al. in 2017. Unlike recurrent or convolutional neural networks, transformers rely entirely on self-attention mechanisms to model sequential data, making them particularly effective for capturing long-range dependencies in musical sequences. The architecture comprises several key components: multi-head self-attention, positional encodings, layer normalization, and feed-forward neural networks.
Self-Attention Mechanism
The self-attention mechanism computes a weighted sum of input embeddings, where the weights are determined by the compatibility between pairs of tokens. Given an input sequence X of dimension dmodel, the mechanism first projects X into queries (Q), keys (K), and values (V) using learned linear transformations:
where WQ, WK, WV are weight matrices of dimension dmodel × dk. The attention scores are computed as:
The scaling factor √dk prevents the dot products from growing too large in magnitude, which would otherwise push the softmax into regions of extremely small gradients.
Multi-Head Attention
Multi-head attention extends self-attention by applying multiple attention mechanisms in parallel, allowing the model to jointly attend to information from different representation subspaces. For h heads, the output is computed as:
where each head is an independent self-attention operation:
and WO is a learned output projection matrix. In MidiBERT, this mechanism enables the model to simultaneously focus on different aspects of musical structure, such as harmony, rhythm, and melody.
Positional Encoding
Since transformers lack inherent sequential processing, positional encodings are added to the input embeddings to inject information about the order of tokens. For a position pos and dimension i, the encoding is defined as:
These sinusoidal functions allow the model to generalize to sequence lengths longer than those encountered during training, a critical feature for handling variable-length musical compositions.
Layer Normalization and Residual Connections
Each sub-layer in the transformer (self-attention, feed-forward network) is followed by layer normalization and a residual connection, which stabilize training and mitigate vanishing gradients. The output of a sub-layer is computed as:
where Sublayer(x) is the function implemented by the sub-layer itself. This architecture ensures smooth gradient flow during backpropagation, even in deep networks.
Feed-Forward Networks
Each transformer layer includes a position-wise feed-forward network (FFN) applied identically to each token. The FFN consists of two linear transformations with a ReLU activation in between:
where W1, W2 are weight matrices and b1, b2 are bias terms. In MidiBERT, the FFN enables non-linear transformations of the attention outputs, capturing complex musical patterns.
By stacking multiple transformer layers, MidiBERT builds hierarchical representations of musical sequences, with lower layers capturing local motifs and higher layers modeling global structure. This architecture has proven particularly effective for tasks such as music generation, classification, and symbolic music understanding.

Tokenization Strategies for MIDI Data
Tokenizing MIDI data for transformer-based models like MidiBERT requires careful consideration of the hierarchical and multi-modal nature of musical sequences. Unlike text, MIDI encodes pitch, velocity, duration, and timing with parallel tracks, necessitating specialized tokenization approaches that preserve musical semantics while enabling efficient sequence modeling.
Event-Based Tokenization
The most common strategy decomposes MIDI into discrete events, each representing a musical action (e.g., note-on, note-off, tempo change). Each event is mapped to a token ID through a vocabulary that typically includes:
- Pitch tokens: 128 values (0–127) corresponding to MIDI note numbers
- Velocity tokens: Quantized into bins (e.g., 32 levels) to reduce sparsity
- Duration tokens: Logarithmically discretized time intervals (e.g., 10ms to 5s in 100 bins)
- Control tokens: Special symbols for track separation, instrumentation, and metadata
Duration quantization uses log-scaling to prioritize precision at shorter note values, with α and β controlling bin distribution. This matches human perceptual sensitivity to rhythmic variations.
Temporal Resolution Handling
MIDI's temporal precision (often 480 ticks per quarter note) requires downsampling to prevent sequence fragmentation. Two dominant approaches:
- Fixed-step quantization: Aligns events to a grid (e.g., 16th notes) using
- Adaptive tokenization: Introduces "time-shift" tokens that encode Δt between events, allowing variable-length intervals without fixed grids
Multi-Track Representation
Polyphonic music requires strategies to handle concurrent tracks. The flattened approach interleaves events from all tracks in temporal order, while hierarchical methods use:
- Track-specific prefix tokens (e.g., [PIANO], [DRUMS])
- Bar-level positional embeddings to maintain vertical alignment
- Cross-attention mechanisms in the model architecture
Vocabulary Construction
The token vocabulary size critically impacts model performance. For a 88-key piano with 32 velocity bins and 100 duration bins, the naive combination would yield 281,600 tokens. Practical implementations use:
- Separate embedding spaces for different event types
- Byte-level or wordpiece-style subword tokenization for rare note combinations
- Dynamic vocabulary pruning based on corpus statistics
Recent variants like Compound Word Tokenization decompose events into attribute sequences (e.g., [NOTE] [C4] [VEL64] [DUR200ms]), reducing vocabulary size while maintaining expressivity.
2.3 Pre-training Objectives and Tasks
Masked Language Modeling (MLM) for Symbolic Music
MidiBERT adapts the Masked Language Modeling (MLM) objective from BERT to symbolic music data. Given a sequence of MIDI events X = (x1, x2, ..., xn), a subset of tokens is randomly masked with probability pmask. The model learns to predict the masked tokens based on the surrounding context. For MIDI data, tokens represent musical elements such as note pitch, velocity, duration, and timing. The loss function for MLM is:
where M is the set of masked positions. Unlike text, MIDI tokens exhibit hierarchical dependencies (e.g., a note's duration depends on its onset timing), requiring the model to capture both local and global musical structure.
Next Sentence Prediction (NSP) Adaptation
While BERT uses NSP to learn relationships between text sentences, MidiBERT replaces this with Next Segment Prediction (NSP), where the model predicts whether two musical segments are contiguous. Given segments S1 and S2, the objective is:
where y = 1 if S2 follows S1 in the original composition, and y = 0 otherwise. This task encourages the model to learn musical coherence beyond local note patterns.
Joint Pitch-Duration Modeling
MIDI events decompose into discrete attributes: pitch p, duration d, and velocity v. MidiBERT extends MLM to predict these attributes jointly. For a masked note, the probability decomposes as:
This factorization reflects musical dependencies—e.g., duration distributions vary by pitch due to instrument-specific idioms.
Contrastive Learning for Musical Similarity
MidiBERT incorporates a contrastive loss to distinguish between positive (musically similar) and negative (dissimilar) segments. Given an anchor segment S, positive sample S+, and negatives S-, the InfoNCE loss is:
where f(·) is the model's embedding, sim is cosine similarity, and τ is a temperature hyperparameter. This objective aligns embeddings for musically equivalent segments (e.g., transposed melodies).
Bar-Level Positional Encoding
To capture metrical structure, MidiBERT uses bar-relative positional encodings. For a note at position t in bar b, the encoding combines:
- Absolute bar position: PEabs(b)
- Relative position within bar: PErel(t mod T), where T is ticks per bar
This dual encoding allows the model to attend to both phrase-level (multi-bar) and beat-synchronous patterns.

3. Datasets for Training MidiBERT
Datasets for Training MidiBERT
Training MidiBERT effectively requires large-scale, high-quality MIDI datasets that capture diverse musical styles, structures, and expressive nuances. The choice of dataset directly impacts the model's ability to generalize across musical genres and tasks such as melody generation, harmonization, or style transfer.
Key MIDI Datasets for MidiBERT
The following datasets are commonly used for training MidiBERT and similar music language models:
- Lakh MIDI Dataset (LMD) — A collection of over 176,000 MIDI files, sourced from various online repositories. LMD is widely used due to its diversity, though it requires preprocessing to filter low-quality or duplicate files. The dataset spans multiple genres, making it suitable for general-purpose music modeling.
- MAESTRO — A high-quality dataset of over 200 hours of piano performances, aligned with audio recordings. MAESTRO is particularly useful for tasks requiring precise timing and expressive dynamics, such as performance rendering or expressive synthesis.
- POP909 — A curated dataset of 909 pop songs with melody and accompaniment annotations. POP909 is ideal for studying harmony and multi-track music generation, as it provides explicit structural labels for chords and melodic lines.
- Classical Archives MIDI Corpus — A specialized dataset focusing on classical music, with over 20,000 compositions. This dataset is valuable for modeling long-term dependencies and complex musical forms inherent in classical repertoire.
Preprocessing MIDI Data for MidiBERT
MIDI files require careful preprocessing to be compatible with transformer-based architectures like MidiBERT. The standard pipeline includes:
-
Quantization — Aligning note onsets and durations to a fixed temporal grid (e.g., 16th notes) to reduce sparsity in the input representation. Given a time resolution δt, each event time t is quantized as:
$$ t_q = \left\lfloor \frac{t}{\delta t} + 0.5 \right\rfloor \cdot \delta t $$
- Tokenization — Converting MIDI events (note-on, note-off, velocity, tempo) into discrete tokens. MidiBERT typically uses a vocabulary of 3,000–5,000 tokens, covering pitch, duration, velocity, and control events.
- Sequence Chunking — Splitting long MIDI sequences into fixed-length segments (e.g., 512 tokens) to fit the transformer's context window. Overlapping segments or sliding windows may be used to preserve continuity.
Dataset Augmentation Strategies
To improve robustness, MIDI datasets are often augmented through:
- Transposition — Shifting all pitches by a fixed interval (±1–11 semitones) to increase key invariance.
- Tempo Scaling — Adjusting global tempo by ±10–20% while preserving relative timing.
- Track Dropping — Randomly omitting accompaniment tracks during training to force the model to learn implicit harmonic relationships.
Evaluation Benchmarks
Standard benchmarks for evaluating MidiBERT's performance include:
- Groove MIDI Dataset — Used for rhythm and timing modeling, with human-performed drum patterns.
- Piano-e-Competition — A collection of virtuosic piano performances for testing high-velocity and polyphonic modeling.
- Symbolic Music Similarity (SMS) Tests — Measures the model's ability to recognize musical similarity and structure.
3.2 Fine-Tuning for Specific Music Tasks
Fine-tuning MidiBERT for specialized music tasks involves adapting its pre-trained representations to downstream applications such as melody generation, chord recognition, or expressive performance modeling. The process leverages transfer learning by initializing the model with weights from pre-training and then updating them on task-specific labeled data. Given MidiBERT's transformer architecture, fine-tuning typically involves modifying the output layer and optimizing the entire model end-to-end.
Task-Specific Architecture Modifications
For classification tasks like genre identification or emotion recognition, a linear projection layer is appended to the [CLS] token's hidden representation:
where Wc and bc are learnable parameters. For sequence labeling tasks (e.g., note-level articulation detection), each token's hidden state is projected:
Optimization Strategy
The loss function combines task-specific objectives with optional regularization. For multi-task learning, a weighted sum of losses is used:
where λi balances task importance and β controls L2 regularization. The learning rate is typically reduced by 10× compared to pre-training, with values between 1e-5 and 5e-5 empirically performing well for music tasks.
Data Augmentation for Music
Effective fine-tuning requires strategies to handle limited labeled music data:
- Transposition invariance: Pitch shifting by ±3 semitones preserves harmonic relationships while expanding diversity.
- Temporal warping: Local tempo variations of ±15% maintain rhythmic structure.
- Voice dropout: Randomly omitting instrument tracks (e.g., removing piano in an ensemble) improves robustness.
Case Study: Expressive Performance Prediction
When fine-tuning for predicting performance attributes (velocity, timing deviations), the model processes aligned score-performance pairs. The input sequence interleaves:
where Score tokens represent nominal note values and Perf tokens encode realized performance features. The model learns cross-modal attention between score and performance contexts.
Computational Considerations
Fine-tuning efficiency can be improved through:
- Gradient checkpointing: Reduces memory usage by 60% at the cost of 25% slower training.
- Mixed-precision training: FP16 operations accelerate training by 1.5–2× on modern GPUs.
- Layer-wise learning rate decay: Lower layers (closer to input) use smaller learning rates (e.g., 0.95 decay factor per layer).
Addressing Challenges in Music Sequence Modeling
Long-Range Dependencies in Polyphonic Music
Music sequences exhibit intricate long-range dependencies, particularly in polyphonic compositions where multiple voices interact simultaneously. Traditional recurrent architectures struggle with these dependencies due to vanishing gradients, while standard attention mechanisms in transformers face quadratic complexity with sequence length. MidiBERT mitigates this by employing relative position embeddings, allowing the model to efficiently capture relationships between distant musical events without explicit positional encoding.
Here, Ri-j represents learnable relative position biases, enabling the model to attend to note patterns regardless of absolute position. This is critical for recognizing motifs or chord progressions that recur across measures.
Hierarchical Structure Modeling
Musical structure operates at multiple timescales—from individual notes to phrases and sections. MidiBERT addresses this through:
- Bar-level masking: Randomly masking entire bars during pretraining forces the model to learn higher-level musical coherence
- Strided attention: Alternating between fine-grained note attention and coarser bar-level attention reduces computational overhead while preserving structural awareness
Discrete Token Representation Challenges
MIDI events are inherently discrete, creating sparse input representations. MidiBERT improves upon this by:
Where pi, di, and vi represent pitch, duration, and velocity embeddings respectively. This disentangled representation allows the model to separately model different musical dimensions while maintaining their interactions through attention.
Temporal Irregularity in Expressive Performances
Human performances introduce microtiming deviations and rubato that challenge rigid sequence models. MidiBERT incorporates:
- Learned tempo embeddings that adapt to local timing variations
- A joint loss function that simultaneously optimizes for note prediction and timing reconstruction
The cross-entropy loss LCE handles discrete note events while mean squared error LMSE captures continuous timing nuances.
Computational Efficiency for Long Sequences
Full-length musical works can span thousands of events. MidiBERT implements:
- Blockwise attention with local context windows
- Memory-compressed attention for global context
- Differentiable resampling of input sequences during training
This maintains O(n log n) complexity while preserving the ability to model complete musical forms.

4. Music Generation and Composition
Music Generation and Composition
Architecture and Tokenization in MidiBERT
MidiBERT employs a transformer-based architecture, leveraging self-attention mechanisms to model sequential dependencies in symbolic music representations. The input is tokenized into discrete events, including:
- Note events (pitch, velocity, duration)
- Control events (tempo, dynamics, articulation)
- Structural markers (bar lines, phrase boundaries)
Each event is embedded into a continuous vector space, enabling the model to capture hierarchical relationships. The tokenization process maps MIDI data into a sequence of integers, analogous to word tokenization in natural language processing.
where n is the sequence length, d is the embedding dimension, and T represents the tokenized input.
Autoregressive Generation with Masked Language Modeling
MidiBERT utilizes a masked language modeling (MLM) objective during pretraining, where random tokens are masked, and the model predicts the missing elements. For generation, the model operates autoregressively, sampling from the output distribution at each step:
where ht is the hidden state at position t, and W, b are learnable parameters. Temperature scaling and top-k sampling are commonly applied to control diversity.
Harmonic and Rhythmic Coherence
The self-attention mechanism enables MidiBERT to learn long-range dependencies critical for maintaining harmonic and rhythmic coherence. Attention heads specialize in different aspects:
- Local attention captures motifs and short phrases
- Global attention maintains structural consistency across sections
- Relative position embeddings preserve temporal relationships
Fine-Tuning for Compositional Tasks
Pretrained MidiBERT can be fine-tuned for specific compositional tasks through:
- Conditional generation (e.g., melody harmonization, style transfer)
- Controllable generation via latent space manipulation
- Multi-task learning combining generation with analysis tasks
where λ1 and λ2 balance pretraining and task-specific objectives.
Evaluation Metrics for Generated Music
Quantitative evaluation employs both objective metrics and human assessment:
- Pitch class histogram entropy measures tonal consistency
- Groove similarity quantifies rhythmic patterns
- Structural segmentation accuracy evaluates form
- Listener studies assess musicality and creativity
where pi represents the probability of pitch class i in the generated piece.

4.2 Music Classification and Tagging
MidiBERT's architecture, derived from BERT's transformer-based framework, is particularly effective for music classification and tagging tasks due to its ability to model sequential dependencies in symbolic music data. The model processes MIDI events as tokens, leveraging self-attention mechanisms to capture long-range harmonic, rhythmic, and structural patterns. For classification, a task-specific head is appended to the pretrained MidiBERT backbone, typically implemented as a multilayer perceptron (MLP) with softmax activation:
where x represents the input MIDI sequence, W and b are learnable parameters, and y denotes the predicted class probabilities. The model is fine-tuned end-to-end using categorical cross-entropy loss:
Feature Extraction for Tagging
For multi-label tagging tasks (e.g., genre, mood, or instrument identification), MidiBERT employs a sigmoid-activated output layer with binary cross-entropy loss. The model extracts hierarchical features at different temporal resolutions:
- Local-level features: Captured by lower transformer layers, encoding note-level attributes like pitch and duration.
- Phrase-level features: Intermediate layers model motifs and short musical phrases.
- Global-level features: Higher layers aggregate structural information about form and style.
Attention Analysis
The self-attention weights reveal interpretable patterns in music understanding. For instance, high attention scores often occur between:
- Melodic sequences and their harmonic accompaniment.
- Rhythically salient events (e.g., downbeats).
- Structurally significant boundaries (e.g., phrase endings).
This attention behavior enables MidiBERT to outperform convolutional and recurrent architectures on tasks like genre classification, where global context is critical. On the GTZAN dataset, MidiBERT achieves 85.2% accuracy, surpassing CNN-based models by 6-8%.
Transfer Learning Applications
Pretrained MidiBERT embeddings can be transferred to downstream tasks with limited labeled data. The embedding space organizes compositions by:
- Metric position (regular vs. syncopated rhythms).
- Tonal center (major vs. minor keys).
- Texture density (homophonic vs. polyphonic).
For few-shot learning, a k-nearest neighbors classifier using MidiBERT embeddings achieves 72% accuracy with only 20 examples per class on the MusicNet dataset.

4.3 Music Transcription and Symbolic Representation
Music transcription involves converting audio signals into symbolic representations such as MIDI or sheet music. MidiBERT leverages transformer architectures to model polyphonic music sequences, capturing both local and global dependencies in symbolic music data. The model treats musical events—notes, chords, and rests—as discrete tokens, enabling it to learn hierarchical structures analogous to language modeling in NLP.
Symbolic Music Representation
MIDI encodes music as a sequence of discrete events, each characterized by attributes like pitch, velocity, and duration. A symbolic representation S of a musical piece can be formalized as a sequence of tokens:
where pi denotes pitch, vi represents velocity (dynamics), and di is duration. MidiBERT tokenizes these attributes into a vocabulary of discrete symbols, enabling the use of transformer-based attention mechanisms.
Event-Based Tokenization
MidiBERT employs an event-based tokenization scheme, where each musical event is decomposed into a series of subtokens. For example, a note-on event is represented as:
- Note-On: A token indicating the start of a note.
- Pitch: A token representing the note's pitch (e.g., C4).
- Velocity: A token encoding the note's intensity.
- Duration: A token specifying how long the note is held.
This fine-grained tokenization allows the model to capture nuanced musical features, such as articulation and phrasing.
Transformer Architecture for Music
MidiBERT adapts the transformer architecture to handle symbolic music sequences. The self-attention mechanism computes relationships between all pairs of tokens, enabling the model to learn long-range dependencies. The attention weights A for a sequence of length L are computed as:
where Q, K, and V are query, key, and value matrices, and dk is the dimension of the key vectors. This mechanism allows MidiBERT to model complex musical structures, such as motifs and harmonic progressions.
Training Objectives
MidiBERT is pre-trained using two primary objectives:
- Masked Token Prediction: Randomly masking tokens and predicting them based on context, akin to BERT's masked language modeling.
- Next-Token Prediction: Predicting the next token in the sequence, similar to autoregressive models like GPT.
These objectives enable the model to learn both bidirectional and sequential dependencies in music.
Applications in Music Transcription
MidiBERT's symbolic understanding facilitates applications such as:
- Automatic Music Transcription: Converting audio performances into MIDI or sheet music.
- Music Generation: Composing new pieces by sampling from the learned distribution.
- Style Transfer: Transforming a piece from one musical style to another.
The model's ability to handle polyphony and complex rhythms makes it particularly suited for classical and jazz music, where precise symbolic representation is critical.

5. Bias in Music Data and Models
5.1 Bias in Music Data and Models
Bias in music data and models manifests in multiple forms, from dataset composition to algorithmic decision-making. MidiBERT, like other transformer-based models, inherits biases present in its training data, which can propagate through tokenization, attention mechanisms, and downstream tasks. Understanding these biases is critical for ensuring fair and representative music generation and analysis.
Sources of Bias in Music Datasets
Training datasets for music models often exhibit imbalances in genre, cultural origin, and composer demographics. For instance, classical MIDI datasets disproportionately represent Western composers, while underrepresented genres like traditional African or Indigenous music are scarce. This skew affects MidiBERT's ability to generalize across diverse musical styles. The tokenization process further compounds this issue by encoding musical elements in ways that favor certain structures—such as 4/4 time signatures or diatonic scales—over others.
Here, \( P(\text{genre} = g \mid \mathcal{D}) \) represents the probability of encountering genre \( g \) in dataset \( \mathcal{D} \), where \( N_g \) is the count of samples for genre \( g \). A model trained on such data will inherently favor overrepresented genres during generation or classification.
Algorithmic Amplification of Bias
MidiBERT's self-attention mechanism can amplify existing biases. Attention weights \( \alpha_{ij} \) between tokens \( i \) and \( j \) are computed as:
If the query (\( Q_i \)) and key (\( K_j \)) vectors are biased toward certain musical patterns, the model will disproportionately attend to those patterns. For example, a preference for chord progressions common in Western pop music might overshadow less frequent but culturally significant progressions in other traditions.
Evaluating and Mitigating Bias
Quantifying bias requires metrics such as genre parity or cultural representativeness. One approach is to measure the Kullback-Leibler (KL) divergence between the model's output distribution \( P_{\text{model}} \) and an ideal uniform distribution \( P_{\text{uniform}} \):
Mitigation strategies include:
- Data augmentation: Synthesizing underrepresented styles using rule-based transformations or style transfer.
- Adversarial debiasing: Training a discriminator to penalize biased attention patterns.
- Re-weighting losses: Assigning higher weights to samples from underrepresented genres during fine-tuning.
Case Study: Bias in Chord Prediction
When MidiBERT predicts chord progressions, it tends to favor major and minor triads over extended or non-tertian harmonies (e.g., quartal or cluster chords). This reflects the prevalence of triadic harmony in its training data. A histogram of predicted chords for a diverse test set often reveals this skew, with diminished or augmented chords appearing less than 5% of the time despite their theoretical importance.
5.2 Intellectual Property and Copyright Issues
The application of MidiBERT in music generation and analysis raises critical intellectual property (IP) and copyright concerns, particularly when the model is trained on existing MIDI datasets. Unlike raw audio, MIDI files encode musical compositions in a structured symbolic format, making them subject to copyright protection under most jurisdictions. The legal landscape becomes complex when considering derivative works generated by the model, as well as potential infringement risks during training.
Training Data and Copyright Infringement
MidiBERT's pretraining typically involves large-scale MIDI datasets, many of which contain copyrighted compositions. Under U.S. law (17 U.S.C. § 106), the reproduction of copyrighted works during training may constitute infringement unless covered by fair use (17 U.S.C. § 107) or licensed appropriately. The four-factor fair use analysis becomes particularly relevant:
- Purpose and character of use: Non-commercial research may favor fair use, but commercial applications weaken this argument.
- Nature of copyrighted work: Creative musical compositions receive stronger protection than factual works.
- Amount and substantiality: Training on entire compositions weighs against fair use.
- Effect on market value: Potential to replace original works is a key consideration.
The European Union's Copyright Directive (Article 4) provides a text and data mining exception for research organizations, but its applicability to AI music models remains untested in court.
Output Generation and Authorship
When MidiBERT generates new musical sequences, determining copyright ownership involves multiple legal questions:
where x is the generated output, y represents copyrighted training examples, and τ is a similarity threshold that may constitute substantial copying. Current U.S. Copyright Office policy states that purely machine-generated works lack human authorship and are therefore ineligible for copyright protection (Compendium § 313.2), though human-AI collaborations may qualify.
Mitigation Strategies
Several technical and legal approaches can reduce IP risks:
- Dataset licensing: Using properly licensed datasets like Lakh MIDI (CC-BY) or creating original compositions for training.
- Filtering mechanisms: Implementing similarity detection to prevent near-identical reproductions of protected works.
- Architectural constraints: Designing attention mechanisms that avoid memorization of complete musical phrases.
- Output screening: Post-generation analysis using tools like Musly or acoustic fingerprinting to detect potential infringements.
The 2023 U.S. Copyright Office guidance on AI-generated works emphasizes that copyright protection requires human creative input that goes beyond mere prompt engineering. This suggests that MidiBERT outputs may need significant human curation or modification to qualify for protection.
International Considerations
Jurisdictional differences create additional complexity. Japan's Copyright Act (Article 30-4) explicitly permits AI training on copyrighted material regardless of purpose, while the UK's Computer Generated Works provision (CDPA 1988 § 9(3)) assigns authorship to the person who made arrangements for the creation. The EU's proposed AI Act may introduce new transparency requirements for training data provenance.
5.3 Limitations of Current Approaches
Current approaches to symbolic music understanding, including transformer-based models like MidiBERT, face several fundamental limitations that hinder their performance and generalizability. These limitations stem from architectural constraints, data representation issues, and computational inefficiencies.
1. Tokenization Challenges
Most symbolic music models rely on tokenization schemes that discretize continuous musical features (e.g., velocity, tempo) into fixed bins. This quantization introduces information loss, particularly for expressive performances where subtle variations carry semantic meaning. The trade-off between vocabulary size and computational efficiency forces models to operate at reduced resolution.
where \(x_i\) represents the original continuous value and \(\hat{x}_i\) its quantized counterpart. This reconstruction error accumulates across sequential predictions.
2. Context Window Constraints
Transformers process music as fixed-length sequences due to the quadratic complexity of self-attention:
where \(n\) is sequence length and \(d\) is embedding dimension. This limits the model's ability to capture long-range musical structures (e.g., sonata form) that may span thousands of tokens. While relative position encoding and sparse attention variants help, they still struggle with hierarchical musical relationships.
3. Lack of Explicit Music Theory Knowledge
Current models learn musical grammar purely from data without incorporating:
- Harmonic rules (e.g., voice leading constraints)
- Formal structures (e.g., A-B-A patterns)
- Instrument-specific idioms
This leads to syntactically valid but musically nonsensical outputs, particularly in few-shot generation scenarios.
4. Multimodal Integration Gaps
Symbolic representations alone cannot capture:
- Timbre variations (critical for orchestration)
- Performance nuances (rubato, articulation)
- Audio-visual correlations (score-following in performances)
Hybrid architectures that jointly model symbolic and audio representations remain computationally prohibitive for most real-world applications.
5. Evaluation Metrics
Standard metrics like perplexity or BLEU scores fail to assess:
- Musical coherence across timescales
- Stylistic authenticity
- Emotional intent realization
The lack of robust evaluation frameworks makes comparative analysis between models particularly challenging.
6. Data Scarcity and Bias
High-quality symbolic music datasets suffer from:
- Overrepresentation of Western classical music
- Limited jazz/folk/indigenous music coverage
- Copyright restrictions on contemporary works
This cultural bias limits the models' ability to generalize across musical traditions.
6. Key Research Papers on MidiBERT
6.1 Key Research Papers on MidiBERT
- MidiBERT-Piano: Large-scale Pre-training for Symbolic Music Understanding — In contrast, relatively less research has been done on music understanding technology for music in symbolic formats such as MusicXML and MIDI. 1 1 1 Musical Instrument Digital Interface; https: ... In this paper, we have presented MidiBERT-Piano, one of the first large-scale pre-trained models for musical data in the MIDI format. ...
- Adversarial-MidiBERT: Symbolic Music Understanding Model Based on ... — Adversarial-MidiBERT: Symbolic Music Understanding Model Based on Unbias Pre-training and Mask Fine-tuning. ... Symbolic Music Understanding (SMU) has been a key research direction within MIR, aiming to assist musicians and amateurs in learning, teaching, and creating music. ... The dataset used in this paper is shown in Table 2. We use five ...
- MidiBERT-Piano: Large-scale Pre-training for Symbolic Music Understanding — MidiBERT-Piano: Large-scale Pre-training for Symbolic Music Understanding Yi-Hui Chou*, I-Chun Chen*, Chin-Jui Chang, Joann Ching, and Yi-Hsuan Yang Abstract—This paper presents an attempt to employ the mask language modeling approach of BERT to pre-train a 12-layer Transformer model over 4,166 pieces of polyphonic piano MIDI
- RS2002/Adversarial-MidiBERT - GitHub — [ICMR 2025] Official Repository for The Paper, Let Network Decide What to Learn: Symbolic Music Understanding Model Based on Large-scale Adversarial Pre-training - RS2002/Adversarial-MidiBERT. Skip to content. Navigation Menu ... This is the official repository for the paper, MidiBERT-Piano: Large-scale Pre-training for Symbolic Music ...
- MidiBERT-Piano - GitHub — This is the official repository for the paper, MidiBERT-Piano: Large-scale Pre-training for Symbolic Music Understanding. With this repository, you can. pre-train a MidiBERT-Piano with your customized pre-trained dataset; fine-tune & evaluate on 4 downstream tasks; extract melody (mid to mid) using pre-trained MidiBERT-Piano
- Papers with Code - BERT-like Pre-training for Symbolic Piano Music ... — Stay informed on the latest trending ML papers with code, research developments, libraries, methods, and datasets. ... This article presents a benchmark study of symbolic piano music classification using the masked language modelling approach of the Bidirectional Encoder Representations from Transformers (BERT). Specifically, we consider two ...
- PDF BERT-like Pre-training for Symbolic Piano Music ... - ResearchGate — Research Center for IT Innovation, Academia Sinica, Taiwan [email protected] Joann Ching Research Center for IT Innovation, Academia Sinica, Taiwan [email protected] Yi-Hsuan Yang
- [2107.05223] BERT-like Pre-training for Symbolic Piano Music ... — This article presents a benchmark study of symbolic piano music classification using the masked language modelling approach of the Bidirectional Encoder Representations from Transformers (BERT). Specifically, we consider two types of MIDI data: MIDI scores, which are musical scores rendered directly into MIDI with no dynamics and precisely aligned with the metrical grid notated by its composer ...
- arXiv:2107.05223v2 [cs.SD] 14 Apr 2024 — fact that all the datasets employed in this work are publicly available, our research can be taken as a new testbed of PTMs in general and a new public benchmark for machine learning-based classification of MIDI music. 2 Related Work on Pre-trained Models for MIDI Machine learning has been applied to music in symbolic formats such as MIDI.
- MidiBERT-Piano: Large-scale Pre-training for Symbolic Music ... — This paper presents a benchmark study of MIDI-domain music classification using the mask language modeling approach of the Bidirectional Encoder Representations from Transformers (BERT).
6.2 Open-Source Implementations and Tools
- MusicBERT - muzic — MusicBERT. MusicBERT: Symbolic Music Understanding with Large-Scale Pre-Training, by Mingliang Zeng, Xu Tan, Rui Wang, Zeqian Ju, Tao Qin, Tie-Yan Liu, ACL 2021, is a large-scale pre-trained model for symbolic music understanding.It has several mechanisms including OctupleMIDI encoding and bar-level masking strategy that are specifically designed for symbolic music data, and achieves state-of ...
- MusicBERT: Symbolic Music Understanding with Large-Scale Pre-Training — Symbolic music understanding, which refers to the understanding of music from the symbolic data (e.g., MIDI format, but not audio), covers many music applications such as genre classification, emotion classification, and music pieces matching. While good music representations are beneficial for these applications, the lack of training data hinders representation learning. Inspired by the ...
- MidiBERT-Piano: Large-scale Pre-training for Symbolic Music Understanding — Our implementation is based on the PyTorch code from the open-source library HuggingFace . Given a corpus of MIDI pieces for pre-training, we use 85% of them for pre-training MidiBERT-Piano as described in Section VII-A , and the rest as the validation set.
- MidiBERT-Piano - GitHub — This is the official repository for the paper, MidiBERT-Piano: Large-scale Pre-training for Symbolic Music Understanding. With this repository, you can. pre-train a MidiBERT-Piano with your customized pre-trained dataset; fine-tune & evaluate on 4 downstream tasks; extract melody (mid to mid) using pre-trained MidiBERT-Piano
- ChanTszKit/MIDI-BERT-2 - GitHub — This is the official repository for the paper, MidiBERT-Piano: Large-scale Pre-training for Symbolic Music Understanding. With this repository, you can pre-train a MidiBERT-Piano with your customized pre-trained dataset fine-tune & evaluate on 4 downstream tasks compare its performance with a Bi ...
- [2107.05223] BERT-like Pre-training for Symbolic Piano Music ... — This article presents a benchmark study of symbolic piano music classification using the masked language modelling approach of the Bidirectional Encoder Representations from Transformers (BERT). Specifically, we consider two types of MIDI data: MIDI scores, which are musical scores rendered directly into MIDI with no dynamics and precisely aligned with the metrical grid notated by its composer ...
- RS2002/Adversarial-MidiBERT - GitHub — Article: Zijian Zhao*, "Let Network Decide What to Learn: Symbolic Music Understanding Model Based on Large-scale Adversarial Pre-training", ACM ICMR 2025. Some parts of our code are based on wazenmai/MIDI
- MidiBERT-Piano: Large-scale Pre-training for Symbolic Music ... — This paper presents a benchmark study of MIDI-domain music classification using the mask language modeling approach of the Bidirectional Encoder Representations from Transformers (BERT).
- 探索音乐新维度:MidiBERT-Piano 开源项目 - CSDN博客 — MidiBERT-Piano的核心是预训练模型MidiBERT,它基于Transformer架构,能对MIDI文件进行大规模的预训练,以学习音乐的深层语义表示。 通过预训练和微调,MidiBERT可以用于音符级任务(如旋律提取)以及序列级任务(如作曲家识别、情感分类)。
- PDF BERT-like Pre-training for Symbolic Piano Music ... - ResearchGate — fine-tuned models publicly in our GitHub repository2 with an open-source licence. Together with the Together with the fact that all the datasets employed in this work are publicly available, our ...
6.3 Recommended Books and Articles on Music AI
- MusicBERT: Symbolic Music Understanding with Large-Scale Pre-Training — Symbolic music understanding, which refers to the understanding of music from the symbolic data (e.g., MIDI format, but not audio), covers many music applications such as genre classification, emotion classification, and music pieces matching. While good music representations are beneficial for these applications, the lack of training data hinders representation learning. Inspired by the ...
- Adversarial-MidiBERT: Symbolic Music Understanding Model Based on ... — Music Information Retrieval (MIR) plays a crucial role in various fields, such as the recommendation systems in music apps and the AI agents for music creation. With the advancement of computer music, symbolic music, which represents music through a structural sequence of notes, has gained widespread attention because most current music is ...
- PDF Musebert: Pre-training of Music Representation for Music Understanding ... — 22nd Int. Society for Music Information Retrieval Conf., Online, 2021. such approach overlooks major distinctions between mu-sic and natural language. Firstly, unlike natural language, music (especially polyphony) does not follow a unique se-quential order; abruptly atten music into a 1-d sequence imposes extra protocol and often undermines the ...
- Handbook of Artificial Intelligence for Music - Springer — Artificial Intelligence (AI) technology permeates the music industry, from management systems for recording studios to recommendation systems for online commercialization of music through the Internet. Yet whereas AI for online music distribution is well advanced, this book focuses on a largely unexplored application: AI for creating the actual ...
- MusicBERT - muzic — MusicBERT. MusicBERT: Symbolic Music Understanding with Large-Scale Pre-Training, by Mingliang Zeng, Xu Tan, Rui Wang, Zeqian Ju, Tao Qin, Tie-Yan Liu, ACL 2021, is a large-scale pre-trained model for symbolic music understanding.It has several mechanisms including OctupleMIDI encoding and bar-level masking strategy that are specifically designed for symbolic music data, and achieves state-of ...
- 4 books on AI for Music [PDF] - AI startups — 1. GRASPED AI in Concert: Shaping the Future Soundscapes of Music 2024 by Steven Brough "GRASPED AI in Concert: Shaping the Future Soundscapes of Music" is less of a book and more of a front-row ticket to the cosmic collision of artificial intelligence and the music industry—think of it as Beethoven meets the Hitchhiker's Guide to AI.
- Understanding Music with AI - MIT Press — The MIT Press has been a leader in open access book publishing for over two decades, beginning in 1995 with the publication of William Mitchell's City of Bits, which appeared simultaneously in print and in a dynamic, open web edition. ... Understanding Music with AI Perspectives on Music Cognition. Edited by Mira Balaban, Kemel Ebcioglu and ...
- GitHub - wazenmai/MIDI-BERT: This is the official repository for the ... — This is the official repository for the paper, MidiBERT-Piano: Large-scale Pre-training for Symbolic Music Understanding. With this repository, you can. pre-train a MidiBERT-Piano with your customized pre-trained dataset; fine-tune & evaluate on 4 downstream tasks; extract melody (mid to mid) using pre-trained MidiBERT-Piano
- [2107.05223] BERT-like Pre-training for Symbolic Piano Music ... — This article presents a benchmark study of symbolic piano music classification using the masked language modelling approach of the Bidirectional Encoder Representations from Transformers (BERT). Specifically, we consider two types of MIDI data: MIDI scores, which are musical scores rendered directly into MIDI with no dynamics and precisely aligned with the metrical grid notated by its composer ...
- MidiBERT-Piano: Large-scale Pre-training for Symbolic Music ... — This article presents a benchmark study of symbolic piano music classification using the masked language modelling approach of the Bidirectional Encoder Representations from Transformers (BER T).








