Upload MidiGen Guitar Pro fine-tune
Browse filesFiles changed (8)
- .gitattributes+1
- LICENSEAdded+10
- README.mdAdded+135
- generate.pyAdded+61
- model.pyAdded+670
- model.safetensorsAdded+3
- requirements.txtAdded+4
- samples/harp.mp3Added+3
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines3334353632 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textsamples/harp.mp3 filter=lfs diff=lfs merge=lfs -text
12345678910Creative Commons Attribution-NonCommercial 4.0 International
Copyright (c) 2026 Praveen Xavier
The MidiGen code and model weights are licensed under the Creative CommonsAttribution-NonCommercial 4.0 International licence to the extent Praveen Xavierholds rights in them.
Licence text: https://creativecommons.org/licenses/by-nc/4.0/legalcode.enPlain-language summary: https://creativecommons.org/licenses/by-nc/4.0/123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135---library_name: pytorchlicense: cc-by-nc-4.0tags:- music- music-generation- symbolic-music- midi- guitar-prodatasets:- Metacreation/GigaMIDI---
# MidiGen: Guitar Pro fine-tune
MidiGen is a 52.3 million parameter PyTorch transformer that continues a shortprompt as multitrack symbolic music. It generates notes for a MIDI file, whichcan be edited in a sequencer or played through a synthesizer.
## Generate a MIDI file
Use Python 3.10 or newer; `requirements.txt` requires PyTorch 2.9 or newer.Download or clone this repository, including `model.safetensors`, and run:
```shpython -m pip install -r requirements.txtpython generate.py --output harp.mid```
The example starts with one middle-C orchestral harp note and generates up to500 additional notes. It uses temperature 1.0 and top-p 0.95. The model canend generation earlier. The script automatically uses CUDA when available andotherwise runs on the CPU.
`generate.py` also accepts `--notes` (maximum number of generated notes,default 500), `--seed` (sampling seed, default 1337, so repeated runs give thesame file) and `--weights` (path to a different `.safetensors` file).
### Example output
This 52-second clip was generated by `generate.py` with its default settingsand rendered to audio with [FluidSynth](https://www.fluidsynth.org/) and the[Arachno SoundFont](https://www.arachnosoft.com/main/soundfont.php). Theinstrument sounds come from the SoundFont, not from the model.
<audio controls src="https://huggingface.co/dennis-xavier/MidiGen/resolve/main/samples/harp.mp3"></audio>
If the player does not appear, [download the MP3 file](samples/harp.mp3).
## Model
This is a custom PyTorch model. `model.py` defines the architecture and theevent format. Each event represents onset delta, track, instrument, pitch, andduration. Melodic instruments use MIDI program numbers and percussion usesseparate instrument and pitch tokens.
The network is a decoder-only transformer with 16 layers, model width 512,8 attention heads, SwiGLU feed-forward layers (width 1408) and RMSNorm. Positionis encoded with rotary embeddings and xPos decay. The context is 2,048 events,with 512-event sliding-window attention. A cascaded output head predicts eachevent one field at a time: onset delta, then track, instrument, pitch andduration, with each prediction conditioned on the fields before it. Weights arestored in float32.
## Training and evaluation
The model was first pretrained for one epoch on[GigaMIDI](https://huggingface.co/datasets/Metacreation/GigaMIDI). Itstraining split contains **2,094,399 songs and 2,463,160,429 note events**, andits held-out split contains 4,184 songs and 5,001,532 note events. No dropoutwas used. The checkpoint with the lowest validation loss was saved at step37,616, after **2,465,202,176 processed events**.
The checkpoint was then fine-tuned on a guitar corpus, because the author likesguitar rhythms and motifs and wanted the model to lean towards them. The corpus is aprivate collection of Guitar Pro files, mostly guitar, bass and drum tracks,and is not redistributed. Its training split contains **47,590 songs and175,342,558 note events**, and its held-out split contains 1,391 songs and5,002,480 note events. Fine-tuning ran for three epochs with 0.1 dropout onembeddings, residual connections and feed-forward layers. Attention-weightdropout stayed at zero so that training could use PyTorch FlexAttention. Thereleased weights are the fine-tuning checkpoint with the lowest validationloss, at step 8,028 after **526,123,008 processed events**. (Bothprocessed-event counts include song-boundary markers, and the fine-tuningcount includes repeated passes over the data.)
On the Guitar Pro held-out split, the released model's next-event validationloss is 0.7555, down from about 0.834 for the pretrained checkpoint. The lossis the sum of the mean cross-entropy losses of the five event fields. Itmeasures how well the model predicts held-out music, not how good its outputsounds.
## Data and release terms
The [Creative Commons Attribution-NonCommercial 4.0 International licence](LICENSE)covers the code and `model.safetensors` to the extent Praveen Xavier holdsrights in them.
[GigaMIDI](https://huggingface.co/datasets/Metacreation/GigaMIDI) retains itsCreative Commons Attribution-NonCommercial 4.0 International licence anddataset access terms. The Guitar Pro files used for fine-tuning retain theterms of their rights holders. The MidiGen licence does not extend to trainingdata or to rights held by third parties.
## Citation
If you use this model, please cite it as:
```bibtex@misc{midigen2026guitarpro, title = {MidiGen: Guitar Pro fine-tune}, author = {Xavier, Praveen}, year = {2026}, howpublished = {\url{https://huggingface.co/dennis-xavier/MidiGen}}}```
Please also cite GigaMIDI:
```bibtex@article{lee2025gigamidi, title = {The GigaMIDI Dataset with Features for Expressive Music Performance Detection}, author = {Lee, Keon Ju Maverick and Ens, Jeff and Adkins, Sara and Sarmento, Pedro and Barthet, Mathieu and Pasquier, Philippe}, journal = {Transactions of the International Society for Music Information Retrieval (TISMIR)}, volume = {8}, number = {1}, pages = {1--19}, year = {2025}}```
## Contact
For questions or feedback, use the model's[Hugging Face Discussions tab](https://huggingface.co/dennis-xavier/MidiGen/discussions).12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061"""Generate a MIDI continuation from a single orchestral harp note."""
import argparsefrom pathlib import Path
import torchfrom safetensors.torch import load_filefrom symusic import Note, Score, Tempo, Track
from model import BPM, DUR_CEIL_SECONDS, N_DUR_BINS, TICKS_PER_S, TPQ, MidiTransformer, _bin_to_seconds
DRUM_PROGRAMS = (0, 8, 16, 24, 25, 32, 40, 48, 56)
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--weights", type=Path, default=Path(__file__).with_name("model.safetensors")) parser.add_argument("--output", type=Path, default=Path("harp.mid")) parser.add_argument("--notes", type=int, default=500, help="Maximum number of continuation notes.") parser.add_argument("--seed", type=int, default=1337, help="Random seed for sampling.") args = parser.parse_args() if args.notes < 1: parser.error("--notes must be positive")
device = torch.device("cuda" if torch.cuda.is_available() else "cpu") model = MidiTransformer() model.load_state_dict(load_file(str(args.weights)), strict=True) model.to(device).eval()
# [onset delta in seconds, track, instrument, pitch, duration in seconds] prompt = torch.tensor([[[0.0, 0.0, 46.0, 60.0, 0.25]]], device=device) torch.manual_seed(args.seed) continuation = model.generate(prompt, args.notes, temperature=1.0, top_p=0.95)
score = Score(TPQ) score.tempos.append(Tempo(0, BPM)) harp = Track(name="Orchestral harp", program=46) harp.notes.append(Note(0, round(0.25 * TICKS_PER_S), 60, 80)) score.tracks.append(harp) tracks = {(0, 46): score.tracks[0]}
onset = 0.0 for delta, track_id, instrument, pitch, duration_bin in continuation: onset += _bin_to_seconds(delta) key = (track_id, instrument) is_drum = instrument >= 128 if key not in tracks: program = DRUM_PROGRAMS[instrument - 128] if is_drum else instrument score.tracks.append(Track(name=f"Track {track_id}", program=program, is_drum=is_drum)) tracks[key] = score.tracks[-1] midi_pitch = max(0, min(127, pitch - 128 if is_drum else pitch)) duration = _bin_to_seconds(duration_bin, N_DUR_BINS, DUR_CEIL_SECONDS) tracks[key].notes.append(Note(round(onset * TICKS_PER_S), max(1, round(duration * TICKS_PER_S)), midi_pitch, 80))
score.dump_midi(str(args.output)) print(f"Saved {args.output} with {len(continuation)} generated notes plus the prompt.")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670#!/usr/bin/env python3"""MidiGen v3 model, masking, binning, and loss helpers."""from __future__ import annotations
import mathimport warningsfrom dataclasses import dataclass
import numpy as npimport torchimport torch.nn as nnimport torch.nn.functional as F
try: from torch.nn.attention.flex_attention import ( BlockMask, create_block_mask, flex_attention as _raw_flex_attention, ) FLEX_ATTENTION_AVAILABLE = True # flex_attention warns and materializes full scores unless compiled. _flex_attention = torch.compile(_raw_flex_attention, dynamic=False)except Exception: BlockMask = None create_block_mask = None _flex_attention = None FLEX_ATTENTION_AVAILABLE = False
_WARNED_FLEX_MASK_FALLBACK = False
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# Model constants# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
D_MODEL = 512N_HEADS = 8assert D_MODEL % N_HEADS == 0HEAD_DIM = D_MODEL // N_HEADS # 64N_LAYERS = 16FFN_DIM = 1408SEQ_LEN = 2048SLIDING_WINDOW = 512DEFAULT_DROPOUT = 0.0XPOS_SCALE_BASE = 512 # attention matrix decays as exp(-distance/XPOS_SCALE_BASE) so we get 1/3 damping at distance=512FLEX_BLOCK_SIZE = 128
D_TIME_EMB = 160D_TRACK_EMB = 32D_INST_EMB = 64D_PITCH_EMB = 160D_DUR_EMB = 96assert D_TIME_EMB + D_TRACK_EMB + D_INST_EMB + D_PITCH_EMB + D_DUR_EMB == D_MODEL
N_TIME_BINS = 140SEP_BIN = N_TIME_BINS # <SEP> index in the time head (total outputs = N_TIME_BINS + 1)N_DUR_BINS = 140TIME_CEIL_SECONDS = 6.0DUR_CEIL_SECONDS = 6.0TIME_LOG_NORM = math.log1p(TIME_CEIL_SECONDS)DUR_LOG_NORM = math.log1p(DUR_CEIL_SECONDS)
N_PITCH_CLASSES = 256N_TRACK_CLASSES = 128N_INSTR_CLASSES = 137
TOP_P = 0.95TEMPERATURE = 1.0
BPM = 120TPQ = 480TICKS_PER_S = BPM / 60.0 * TPQ # 960 ticks/s at 120 BPM
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# Utility functions# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def build_rope_freqs( seq_len: int, head_dim: int, device: torch.device, start_pos: int = 0,) -> torch.Tensor: """Returns [seq_len, head_dim] RoPE frequency cache for absolute positions.""" half = head_dim // 2 theta = 1.0 / (10000 ** (torch.arange(0, half, device=device).float() / half)) t = torch.arange(start_pos, start_pos + seq_len, device=device).float() freqs = torch.outer(t, theta) # [seq_len, half] return torch.cat([freqs, freqs], dim=-1) # [seq_len, head_dim]
def build_xpos_scale( seq_len: int, device: torch.device, scale_base: float = XPOS_SCALE_BASE, start_pos: int = 0,) -> torch.Tensor: """Returns uniform xPos scale [seq_len, 1] for stable absolute positions.""" center = SEQ_LEN // 2 pos = torch.arange(start_pos, start_pos + seq_len, device=device).float() return torch.exp((pos - center) / scale_base)[:, None]
def rotate_half(x: torch.Tensor) -> torch.Tensor: h = x.shape[-1] // 2 return torch.cat([-x[..., h:], x[..., :h]], dim=-1)
def apply_rope( x: torch.Tensor, freqs: torch.Tensor, scale: torch.Tensor | None = None,) -> torch.Tensor: """x: [B, H, T, D], freqs: [T, D], scale: optional [T, 1].""" cos = freqs.cos().to(dtype=x.dtype)[None, None] sin = freqs.sin().to(dtype=x.dtype)[None, None] out = x * cos + rotate_half(x) * sin if scale is not None: out = out * scale.to(dtype=x.dtype)[None, None] return out
def _sample_top_p(logits: torch.Tensor, p: float, temperature: float) -> torch.Tensor: """Top-P (nucleus) sampling. logits: [..., V] β sampled indices [...].""" logits = logits / temperature probs = F.softmax(logits, dim=-1) sorted_probs, sorted_idx = probs.sort(dim=-1, descending=True) cum = sorted_probs.cumsum(dim=-1) sorted_probs[cum - sorted_probs > p] = 0.0 sorted_probs /= sorted_probs.sum(dim=-1, keepdim=True).clamp(min=1e-8) flat_p = sorted_probs.reshape(-1, sorted_probs.shape[-1]) sampled = torch.multinomial(flat_p, 1).reshape(*logits.shape[:-1]) # [...] flat_idx = sorted_idx.reshape(-1, sorted_idx.shape[-1]) bi = torch.arange(sampled.numel(), device=logits.device) return flat_idx[bi, sampled.reshape(-1)].reshape(sampled.shape)
def _seconds_to_bin( x: torch.Tensor, n_bins: int, ceil_seconds: float = TIME_CEIL_SECONDS,) -> torch.Tensor: """Map raw seconds to integer bins [0, n_bins - 1] with the model's log time scale.""" log_norm = math.log1p(ceil_seconds) return (torch.log1p(x.clamp(0.0, ceil_seconds)) / log_norm * (n_bins - 1)).round().long()
def notes_to_input_bins(notes: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: """Convert raw note rows to categorical input bins for embedding.""" is_sep = notes[:, :, 0] < 0.0 time_bins = _seconds_to_bin(notes[:, :, 0], N_TIME_BINS) time_bins = torch.where(is_sep, time_bins.new_full(time_bins.shape, SEP_BIN), time_bins)
track_bins = notes[:, :, 1].round().long().clamp(0, N_TRACK_CLASSES - 1) track_bins = torch.where(is_sep, track_bins.new_zeros(track_bins.shape), track_bins)
inst_bins = notes[:, :, 2].round().long().clamp(0, N_INSTR_CLASSES - 1) inst_bins = torch.where(is_sep, inst_bins.new_zeros(inst_bins.shape), inst_bins)
pitch_bins = notes[:, :, 3].round().long().clamp(0, N_PITCH_CLASSES - 1) pitch_bins = torch.where(is_sep, pitch_bins.new_zeros(pitch_bins.shape), pitch_bins)
dur_bins = _seconds_to_bin(notes[:, :, 4], N_DUR_BINS, DUR_CEIL_SECONDS) dur_bins = torch.where(is_sep, dur_bins.new_zeros(dur_bins.shape), dur_bins) return time_bins, track_bins, inst_bins, pitch_bins, dur_bins
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# Model components# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@dataclassclass AttentionContext: bool_mask: torch.Tensor | None = None block_mask: BlockMask | None = None is_causal: bool = True
def _causal_sliding_bool_mask( q_len: int, key_len: int, device: torch.device, window: int = SLIDING_WINDOW,) -> torch.Tensor: q_pos = key_len - q_len + torch.arange(q_len, device=device) k_pos = torch.arange(key_len, device=device) distance = q_pos[:, None] - k_pos[None, :] return (distance >= 0) & (distance < int(window))
def _build_doc_attention_context( doc_ids: torch.Tensor | None, *, device: torch.device, seq_len: int, prefer_flex: bool = True,) -> AttentionContext | None: if doc_ids is None: return None
doc_ids = doc_ids.to(device=device) if prefer_flex and FLEX_ATTENTION_AVAILABLE and create_block_mask is not None and device.type == "cuda": try: def doc_mask_mod( b: torch.Tensor, h: torch.Tensor, q_idx: torch.Tensor, kv_idx: torch.Tensor, ) -> torch.Tensor: distance = q_idx - kv_idx return ( (distance >= 0) & (distance < SLIDING_WINDOW) & (doc_ids[b, q_idx] == doc_ids[b, kv_idx]) )
return AttentionContext( block_mask=create_block_mask( doc_mask_mod, B=doc_ids.shape[0], H=None, Q_LEN=seq_len, KV_LEN=seq_len, device=device, BLOCK_SIZE=FLEX_BLOCK_SIZE, _compile=True, ), is_causal=False, ) except Exception as exc: global _WARNED_FLEX_MASK_FALLBACK if not _WARNED_FLEX_MASK_FALLBACK: warnings.warn( "flex_attention block-mask creation failed; falling back to " f"SDPA with a dense bool mask. Error: {type(exc).__name__}: {exc}", RuntimeWarning, stacklevel=2, ) _WARNED_FLEX_MASK_FALLBACK = True
causal_window = _causal_sliding_bool_mask(seq_len, seq_len, device) same_doc = doc_ids[:, :, None] == doc_ids[:, None, :] return AttentionContext( bool_mask=same_doc[:, None, :, :] & causal_window[None, None, :, :], is_causal=False, )
class NoteEmbedder(nn.Module): """Maps float note tensors [B, T, 5] to categorical embeddings."""
def __init__(self): super().__init__() self.sep_embedding = nn.Parameter(torch.zeros(D_MODEL)) self.time_embed = nn.Embedding(N_TIME_BINS + 1, D_TIME_EMB) self.track_embed = nn.Embedding(N_TRACK_CLASSES, D_TRACK_EMB) self.inst_embed = nn.Embedding(N_INSTR_CLASSES, D_INST_EMB) self.pitch_embed = nn.Embedding(N_PITCH_CLASSES, D_PITCH_EMB) self.dur_embed = nn.Embedding(N_DUR_BINS, D_DUR_EMB)
def forward(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: """Returns (emb [B, T, D_MODEL], is_sep [B, T]).""" is_sep = x[:, :, 0] < 0.0 time_b, track_b, inst_b, pitch_b, dur_b = notes_to_input_bins(x) emb = torch.cat([ self.time_embed(time_b), self.track_embed(track_b), self.inst_embed(inst_b), self.pitch_embed(pitch_b), self.dur_embed(dur_b), ], dim=-1) emb = torch.where(is_sep[:, :, None], self.sep_embedding[None, None, :], emb) return emb, is_sep
class CausalSelfAttention(nn.Module):
def __init__(self, dropout: float = DEFAULT_DROPOUT): super().__init__() self.qkv = nn.Linear(D_MODEL, 3 * D_MODEL, bias=False) self.proj = nn.Linear(D_MODEL, D_MODEL, bias=False) self.dropout_p = float(dropout)
def forward( self, x: torch.Tensor, rope_freqs: torch.Tensor, xpos_scale: torch.Tensor, attn_context: AttentionContext | None = None, kv_cache: tuple[torch.Tensor, torch.Tensor] | None = None, use_cache: bool = False, ) -> torch.Tensor | tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor]]: B, T, _ = x.shape q, k, v = self.qkv(x).reshape(B, T, 3, N_HEADS, HEAD_DIM).unbind(2) q = apply_rope(q.transpose(1, 2), rope_freqs, 1.0 / xpos_scale) # [B, H, T, D] k = apply_rope(k.transpose(1, 2), rope_freqs, xpos_scale) v = v.transpose(1, 2)
past_len = 0 if kv_cache is not None: past_k, past_v = kv_cache past_len = past_k.shape[-2] k = torch.cat([past_k, k], dim=-2) v = torch.cat([past_v, v], dim=-2)
if kv_cache is not None and use_cache and k.shape[-2] > SLIDING_WINDOW: k = k[:, :, -SLIDING_WINDOW:, :] v = v[:, :, -SLIDING_WINDOW:, :] past_len = max(0, k.shape[-2] - T)
key_len = k.shape[-2] if attn_context is not None: if key_len != T: raise ValueError("document masking is not supported with a non-empty KV cache") if attn_context.block_mask is not None: if _flex_attention is None: raise RuntimeError("attention context has a block mask but flex_attention is unavailable") out = _flex_attention(q, k, v, block_mask=attn_context.block_mask) out = self.proj(out.transpose(1, 2).reshape(B, T, D_MODEL)) if use_cache: return out, (k, v) return out elif attn_context.bool_mask is not None: attn_mask = attn_context.bool_mask is_causal = attn_context.is_causal else: raise RuntimeError("attention context has no usable mask") elif past_len: attn_mask = _causal_sliding_bool_mask(T, key_len, x.device)[None, None, :, :] is_causal = False else: attn_mask = _causal_sliding_bool_mask(T, key_len, x.device)[None, None, :, :] is_causal = False out = F.scaled_dot_product_attention( q, k, v, attn_mask=attn_mask, dropout_p=self.dropout_p if self.training else 0.0, is_causal=is_causal, ) out = self.proj(out.transpose(1, 2).reshape(B, T, D_MODEL)) if use_cache: if k.shape[-2] > SLIDING_WINDOW: k = k[:, :, -SLIDING_WINDOW:, :] v = v[:, :, -SLIDING_WINDOW:, :] return out, (k, v) return out
class RMSNorm(nn.Module):
def __init__(self, dim: int, eps: float = 1e-6): super().__init__() self.eps = eps self.weight = nn.Parameter(torch.ones(dim))
def forward(self, x: torch.Tensor) -> torch.Tensor: rms = x.pow(2).mean(dim=-1, keepdim=True).add(self.eps).rsqrt() return x * rms * self.weight
class SwiGLUFeedForward(nn.Module):
def __init__(self, dropout: float = DEFAULT_DROPOUT): super().__init__() self.gate = nn.Linear(D_MODEL, FFN_DIM) self.up = nn.Linear(D_MODEL, FFN_DIM) self.down = nn.Linear(FFN_DIM, D_MODEL) self.drop = nn.Dropout(dropout)
def forward(self, x: torch.Tensor) -> torch.Tensor: return self.down(self.drop(F.silu(self.gate(x)) * self.up(x)))
class TransformerBlock(nn.Module):
def __init__(self, dropout: float = DEFAULT_DROPOUT, *, attention_dropout: float | None = None): super().__init__() self.norm1 = RMSNorm(D_MODEL) self.attn = CausalSelfAttention(dropout if attention_dropout is None else attention_dropout) self.norm2 = RMSNorm(D_MODEL) self.ffn = SwiGLUFeedForward(dropout) self.drop = nn.Dropout(dropout)
def forward( self, x: torch.Tensor, rope_freqs: torch.Tensor, xpos_scale: torch.Tensor, attn_context: AttentionContext | None = None, kv_cache: tuple[torch.Tensor, torch.Tensor] | None = None, use_cache: bool = False, ) -> torch.Tensor | tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor]]: attn_out = self.attn(self.norm1(x), rope_freqs, xpos_scale, attn_context, kv_cache, use_cache) new_cache = None if use_cache: attn_tensor, new_cache = attn_out else: attn_tensor = attn_out x = x + self.drop(attn_tensor) x = x + self.drop(self.ffn(self.norm2(x))) if use_cache: return x, new_cache return x
class CascadedHead(nn.Module): """Intra-event categorical output head: Time -> Track -> Instrument -> Pitch -> Duration."""
def __init__(self): super().__init__() self.time_head = nn.Linear(D_MODEL, N_TIME_BINS + 1) self.time_to_track_embed = nn.Embedding(N_TIME_BINS + 1, D_MODEL) self.track_head = nn.Linear(D_MODEL, N_TRACK_CLASSES) self.track_to_inst_embed = nn.Embedding(N_TRACK_CLASSES, D_MODEL) self.inst_head = nn.Linear(D_MODEL, N_INSTR_CLASSES) self.inst_to_pitch_embed = nn.Embedding(N_INSTR_CLASSES, D_MODEL) self.pitch_head = nn.Linear(D_MODEL, N_PITCH_CLASSES) self.pitch_to_dur_embed = nn.Embedding(N_PITCH_CLASSES, D_MODEL) self.dur_head = nn.Linear(D_MODEL, N_DUR_BINS)
def forward( self, h: torch.Tensor, tgt_time_bin: torch.Tensor, tgt_track_bin: torch.Tensor, tgt_inst_bin: torch.Tensor, tgt_pitch_bin: torch.Tensor, ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
time_logits = self.time_head(h) c_track = h + self.time_to_track_embed(tgt_time_bin.clamp(0, SEP_BIN)) track_logits = self.track_head(c_track)
track_for_inst = tgt_track_bin.clamp(0, N_TRACK_CLASSES - 1) c_inst = c_track + self.track_to_inst_embed(track_for_inst) inst_logits = self.inst_head(c_inst)
inst_for_pitch = tgt_inst_bin.clamp(0, N_INSTR_CLASSES - 1) c_pitch = c_inst + self.inst_to_pitch_embed(inst_for_pitch) pitch_logits = self.pitch_head(c_pitch)
pitch_for_dur = tgt_pitch_bin.clamp(0, N_PITCH_CLASSES - 1) c_dur = c_pitch + self.pitch_to_dur_embed(pitch_for_dur) dur_logits = self.dur_head(c_dur) return time_logits, track_logits, inst_logits, pitch_logits, dur_logits
class MidiTransformer(nn.Module):
def __init__(self, dropout: float = DEFAULT_DROPOUT, *, attention_dropout: float | None = None): super().__init__() self.dropout = float(dropout) self.attention_dropout = self.dropout if attention_dropout is None else float(attention_dropout) if not 0.0 <= self.attention_dropout <= 1.0: raise ValueError("attention_dropout must be between 0 and 1") self.embedder = NoteEmbedder() self.drop = nn.Dropout(dropout) self.blocks = nn.ModuleList([ TransformerBlock(dropout, attention_dropout=self.attention_dropout) for _ in range(N_LAYERS) ]) self.norm = RMSNorm(D_MODEL) self.head = CascadedHead() self._init_weights()
def _init_weights(self): for m in self.modules(): if isinstance(m, nn.Linear): nn.init.normal_(m.weight, std=0.02) if m.bias is not None: nn.init.zeros_(m.bias) elif isinstance(m, nn.Embedding): nn.init.normal_(m.weight, std=0.02) elif isinstance(m, RMSNorm): nn.init.ones_(m.weight) nn.init.normal_(self.embedder.sep_embedding, std=0.02)
def _encode( self, x: torch.Tensor, doc_ids: torch.Tensor | None = None, kv_cache: list[tuple[torch.Tensor, torch.Tensor] | None] | None = None, start_pos: int = 0, use_cache: bool = False, ) -> torch.Tensor | tuple[torch.Tensor, list[tuple[torch.Tensor, torch.Tensor]]]: """x: [B, T, 5] -> h: [B, T, D_MODEL]. Optionally returns updated KV cache.""" emb, _ = self.embedder(x) h = self.drop(emb) freqs = build_rope_freqs(x.shape[1], HEAD_DIM, x.device, start_pos=start_pos) xpos_scale = build_xpos_scale(x.shape[1], x.device, start_pos=start_pos) new_cache: list[tuple[torch.Tensor, torch.Tensor]] = [] if kv_cache is None: kv_cache = [None] * len(self.blocks) attn_context = _build_doc_attention_context( doc_ids, device=x.device, seq_len=x.shape[1], prefer_flex=not (self.training and self.attention_dropout > 0.0), ) for idx, block in enumerate(self.blocks): if use_cache: h, layer_cache = block(h, freqs, xpos_scale, attn_context, kv_cache[idx], use_cache=True) new_cache.append(layer_cache) else: h = block(h, freqs, xpos_scale, attn_context) h = self.norm(h) if use_cache: return h, new_cache return h
def forward( self, x: torch.Tensor, # [B, T, 5] inputs targets: torch.Tensor, # [B, T, 5] next-step targets doc_ids: torch.Tensor | None = None, ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: h = self._encode(x, doc_ids) tgt_time, tgt_track, tgt_inst, tgt_pitch, _ = bin_targets(targets) return self.head(h, tgt_time, tgt_track, tgt_inst, tgt_pitch)
@torch.no_grad() def generate( self, seed: torch.Tensor, n_notes: int, top_p: float = TOP_P, temperature: float = TEMPERATURE, ) -> list[tuple]: """seed: [1, T, 5]. Returns integer (time, track, instrument, pitch, duration) bins.""" self.eval() device = seed.device ctx = seed[:, -SEQ_LEN:, :].clone() notes: list[tuple[int, int, int, int, int]] = [] h, kv_cache = self._encode(ctx, start_pos=0, use_cache=True) h_last = h[:, -1:, :] # [1, 1, D_MODEL] next_pos = ctx.shape[1]
for _ in range(n_notes): # Time time_logits = self.head.time_head(h_last) time_bin = _sample_top_p(time_logits, top_p, temperature).item() if int(time_bin) == SEP_BIN: break
# Track tb = torch.tensor([[int(time_bin)]], dtype=torch.long, device=device) c_track = h_last + self.head.time_to_track_embed(tb) track_bin = int(_sample_top_p(self.head.track_head(c_track), top_p, temperature).item())
# Instrument tr = torch.tensor([[track_bin]], dtype=torch.long, device=device) c_inst = c_track + self.head.track_to_inst_embed(tr) inst_bin = int(_sample_top_p(self.head.inst_head(c_inst), top_p, temperature).item())
# Pitch it = torch.tensor([[inst_bin]], dtype=torch.long, device=device) c_pitch = c_inst + self.head.inst_to_pitch_embed(it) pitch_logits = self.head.pitch_head(c_pitch) pitch_bin = int(_sample_top_p(pitch_logits, top_p, temperature).item())
# Duration pt = torch.tensor([[pitch_bin]], dtype=torch.long, device=device) c_dur = c_pitch + self.head.pitch_to_dur_embed(pt) dur_bin = int(_sample_top_p(self.head.dur_head(c_dur), top_p, temperature).item())
note = (int(time_bin), track_bin, inst_bin, pitch_bin, dur_bin) notes.append(note)
next_tok = torch.tensor( [[[ _bin_to_seconds(note[0]), float(note[1]), float(note[2]), float(note[3]), _bin_to_seconds(note[4], N_DUR_BINS, DUR_CEIL_SECONDS), ]]], dtype=torch.float32, device=device, ) h, kv_cache = self._encode( next_tok, kv_cache=kv_cache, start_pos=next_pos, use_cache=True, ) h_last = h[:, -1:, :] next_pos += 1
return notes
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# Loss function# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def bin_targets(targets: torch.Tensor): """targets: [B, T, 5] -> (time, track, instrument, pitch, duration) bins, all [B, T] int64.""" is_sep = targets[:, :, 0] < 0.0
time_bins = _seconds_to_bin(targets[:, :, 0], N_TIME_BINS) time_bins = torch.where(is_sep, time_bins.new_full(time_bins.shape, SEP_BIN), time_bins)
track_bins = targets[:, :, 1].round().long().clamp(0, N_TRACK_CLASSES - 1) track_bins = torch.where(is_sep, track_bins.new_full(track_bins.shape, -100), track_bins)
inst_bins = targets[:, :, 2].round().long().clamp(0, N_INSTR_CLASSES - 1) inst_bins = torch.where(is_sep, inst_bins.new_full(inst_bins.shape, -100), inst_bins)
pitch_bins = targets[:, :, 3].round().long().clamp(0, N_PITCH_CLASSES - 1) pitch_bins = torch.where(is_sep, pitch_bins.new_full(pitch_bins.shape, -100), pitch_bins)
dur_bins = _seconds_to_bin(targets[:, :, 4], N_DUR_BINS, DUR_CEIL_SECONDS) dur_bins = torch.where(is_sep, dur_bins.new_full(dur_bins.shape, -100), dur_bins)
return time_bins, track_bins, inst_bins, pitch_bins, dur_bins
_CE = nn.CrossEntropyLoss( ignore_index=-100, reduction="none",)
def compute_loss( time_l, track_l, inst_l, pitch_l, dur_l, time_b, track_b, inst_b, pitch_b, dur_b, loss_mask: torch.Tensor | None = None,): if loss_mask is None: loss_mask = torch.ones_like(time_b, dtype=torch.bool) else: loss_mask = loss_mask.to(device=time_b.device, dtype=torch.bool)
def f(logits, bins): flat_bins = bins.reshape(-1) flat_loss = _CE(logits.reshape(-1, logits.shape[-1]), flat_bins) active = loss_mask.reshape(-1) & (flat_bins != -100) denom = active.sum().clamp(min=1) return flat_loss[active].sum() / denom
return ( f(time_l, time_b) + f(track_l, track_b) + f(inst_l, inst_b) + f(pitch_l, pitch_b) + f(dur_l, dur_b) )
def document_ids_and_loss_mask(chunk: np.ndarray) -> tuple[np.ndarray, np.ndarray]: """Return token document ids and active target mask for a packed chunk.
SEP belongs to the document before it. The token after a SEP starts a new document, so the SEP -> next-track transition is masked out of the loss. """ is_sep = chunk[:, 0] < 0.0 doc_ids = np.concatenate(([0], np.cumsum(is_sep[:-1], dtype=np.int64))).astype(np.int64) loss_mask = doc_ids[:-1] == doc_ids[1:] return doc_ids[:-1], loss_mask
def _bin_to_seconds( bin_idx: int, n_bins: int = N_TIME_BINS, ceil_seconds: float = TIME_CEIL_SECONDS,) -> float: """Map a time/duration bin [0, n_bins - 1] to seconds via inverse log-norm.""" log_norm = math.log1p(ceil_seconds) return min(math.exp((bin_idx / (n_bins - 1)) * log_norm) - 1.0, ceil_seconds)123version https://git-lfs.github.com/spec/v1oid sha256:f48ce8b30f47880d3cbcc78c6b0b75a56744662a680b2b8e85282fd3935039c1size 2091814561234torch>=2.9numpy>=1.26safetensors>=0.5symusic>=0.4123version https://git-lfs.github.com/spec/v1oid sha256:580d141b322ca17d3bf19565b1f4473102307cff77424dc7f09c73d796b1b5f4size 1035397.gitattributes+1
LICENSEAdded+10
README.mdAdded+135
generate.pyAdded+61
model.pyAdded+670
model.safetensorsAdded+3
requirements.txtAdded+4
samples/harp.mp3Added+3