Views
No views yet

midisim_small_pre_trained_model_2_epochs_43117_steps_0.3148_loss_0.9229_acc.pth - Very fast and accurate small model, suitable for all tasks. This model is included in PyPI package or it can be downloaded from Hugging Facemidisim_large_pre_trained_model_2_epochs_86275_steps_0.2054_loss_0.9385_acc.pth - Fast large model for more nuanced embeddings generation. Download checkpoint from Hugging Facediscover_midi_dataset_37292_genres_midis_embeddings_cc_by_nc_sa.npy - 37292 genre MIDIs embeddings for genre (artist and song) identification tasksdiscover_midi_dataset_202400_identified_midis_embeddings_cc_by_nc_sa.npy - 202400 identified MIDIs embeddings for MIDI identification tasksdiscover_midi_dataset_3480123_clean_midis_embeddings_cc_by_nc_sa.npy - 3480123 select clean MIDIs embeddings for large scale similarity search and analysis tasksdiscover_midi_dataset_37302_genre_midis_embeddings_1_1_2_weighted_cc_by_nc_sa.npy - 37302 genre MIDIs weighted embeddings for genre (artist and song) identification tasksdiscover_midi_dataset_190032_identified_midis_embeddings_1_1_2_weighted_cc_by_nc_sa.npy - 190032 identified MIDIs weighted embeddings for MIDI identification tasksdiscover_midi_dataset_3480123_clean_midis_embeddings_1_1_2_weighted_cc_by_nc_sa.npy - 3480123 select clean MIDIs weighted embeddings for large scale similarity search and analysis tasksdiscover_midi_dataset_37303_genres_midis_embeddings_large_cc_by_nc_sa.npy - 37303 genre MIDIs embeddings for genre (artist and song) identification tasksdiscover_midi_dataset_202400_identified_midis_embeddings_large_cc_by_nc_sa.npy - 202400 identified MIDIs embeddings for MIDI identification tasksdiscover_midi_dataset_3480123_clean_midis_embeddings_large_cc_by_nc_sa.npy - 3480123 select clean MIDIs embeddings for large scale similarity search and analysis tasksdiscover_midi_dataset_37287_genres_midis_embeddings_1_1_2_weighted_large_cc_by_nc_sa.npy - 37287 genre MIDIs weighted embeddings for genre (artist and song) identification tasksdiscover_midi_dataset_190032_identified_midis_embeddings_1_1_2_weighted_large_cc_by_nc_sa.npy - 190032 identified MIDIs weighted embeddings for MIDI identification tasksdiscover_midi_dataset_3480123_clean_midis_embeddings_1_1_2_weighted_large_cc_by_nc_sa.npy - 3480123 select clean MIDIs weighted embeddings for large scale similarity search and analysis tasksmidisim-similarity-search-output-samples-CC-BY-NC-SA.zip - ~300000 MIDIs indentified with midisim music discovery pipeline with both pre-trained modelsmidisim-similarity-search-output-samples-1-1-2-weighted-CC-BY-NC-SA.zip - ~366000 MIDIs indentified with weighted midisim music discovery pipeline with both pre-trained models!pip install -U midisim!pip install x-transformers==2.3.11# ================================================================================================
2# Initalize midisim
3# ================================================================================================
4
5# Import main midisim module
6import midisim
7
8# ================================================================================================
9# Prepare midisim embeddings
10# ================================================================================================
11
12# Option 1: Download sample pre-computed embeddings corpus from Hugging Face
13emb_path = midisim.download_embeddings()
14
15# Option 2: use custom pre-computed embeddings corpus
16# See custom embeddings generation section of this README for details
17# emb_path = './custom_midis_embeddings_corpus.npy'
18
19# Load downloaded embeddings corpus
20corpus_midi_names, corpus_emb = midisim.load_embeddings(emb_path)
21
22# ================================================================================================
23# Prepare midisim model
24# ================================================================================================
25
26# Option 1: Download main pre-trained midisim model from Hugging Face
27model_path = midisim.download_model()
28
29# Option 2: Use main pre-trained midisim model included in midisim PyPI package
30# model_path = midisim.get_package_models()[0]['path']
31
32# Load midisim model
33model, ctx, dtype = midisim.load_model(model_path)
34
35# ================================================================================================
36# Prepare source MIDI
37# ================================================================================================
38
39# Load source MIDI
40input_toks_seqs = midisim.midi_to_tokens('Come To My Window.mid')
41
42# ================================================================================================
43# Calculate and analyze embeddings
44# ================================================================================================
45
46# Compute source/query embeddings
47query_emb = midisim.get_embeddings_bf16(model, input_toks_seqs)
48
49# Calculate cosine similarity between source/query MIDI embeddings and embeddings corpus
50idxs, sims = midisim.cosine_similarity_topk(query_emb, corpus_emb)
51
52# ================================================================================================
53# Processs, print and save results
54# ================================================================================================
55
56# Convert the results to sorted list with transpose values
57idxs_sims_tvs_list = midisim.idxs_sims_to_sorted_list(idxs, sims)
58
59# Print corpus matches (and optionally) convert the final result to a handy list for further processing
60corpus_matches_list = midisim.print_sorted_idxs_sims_list(idxs_sims_tvs_list, corpus_midi_names, return_as_list=True)
61
62# ================================================================================================
63# Copy matched MIDIs from the MIDI corpus for listening and further evaluation and analysis
64# ================================================================================================
65
66# Copy matched corpus MIDI to a desired directory for easy evaluation and analysis
67out_dir_path = midisim.copy_corpus_files(corpus_matches_list)
68
69# ================================================================================================1import torch
2from x_transformers import TransformerWrapper, Encoder
3
4# Original model hyperparameters
5SEQ_LEN = 3072
6
7MASK_IDX = 384 # Use this value for masked modelling
8PAD_IDX = 385 # Model pad index
9VOCAB_SIZE = 386 # Total vocab size
10
11MASK_PROB = 0.15 # Original training mask probability value (use for masked modelling)
12
13DEVICE = 'cuda' # You can use any compatible device or CPU
14DTYPE = torch.bfloat16 # Original training dtype
15
16# Official main midisim model checkpoint name
17MODEL_CKPT = 'midisim_small_pre_trained_model_2_epochs_43117_steps_0.3148_loss_0.9229_acc.pth'
18
19# Model architecture using x-transformers
20model = TransformerWrapper(
21 num_tokens = VOCAB_SIZE,
22 max_seq_len = SEQ_LEN,
23 attn_layers = Encoder(
24 dim = 512,
25 depth = 8,
26 heads = 8,
27 rotary_pos_emb = True,
28 attn_flash = True,
29 ),
30)
31
32model.load_state_dict(torch.load(MODEL_CKPT, map_location=DEVICE))
33
34model.to(DEVICE)
35model.eval()
36
37# Original training autoxast setup
38autocast_ctx = torch.amp.autocast(device_type=DEVICE, dtype=DTYPE)1import torch
2from x_transformers import TransformerWrapper, Encoder
3
4# Original model hyperparameters
5SEQ_LEN = 3072
6
7MASK_IDX = 384 # Use this value for masked modelling
8PAD_IDX = 385 # Model pad index
9VOCAB_SIZE = 386 # Total vocab size
10
11MASK_PROB = 0.15 # Original training mask probability value (use for masked modelling)
12
13DEVICE = 'cuda' # You can use any compatible device or CPU
14DTYPE = torch.bfloat16 # Original training dtype
15
16# Official main midisim model checkpoint name
17MODEL_CKPT = 'midisim_large_pre_trained_model_2_epochs_86275_steps_0.2054_loss_0.9385_acc.pth'
18
19# Model architecture using x-transformers
20model = TransformerWrapper(
21 num_tokens = VOCAB_SIZE,
22 max_seq_len = SEQ_LEN,
23 attn_layers = Encoder(
24 dim = 512,
25 depth = 16,
26 heads = 8,
27 rotary_pos_emb = True,
28 attn_flash = True,
29 ),
30)
31
32model.load_state_dict(torch.load(MODEL_CKPT, map_location=DEVICE))
33
34model.to(DEVICE)
35model.eval()
36
37# Original training autoxast setup
38autocast_ctx = torch.amp.autocast(device_type=DEVICE, dtype=DTYPE)1# ================================================================================================
2
3# Load main midisim module
4import midisim
5
6# Import helper modules
7import os
8import tqdm
9
10# ================================================================================================
11
12# Call included TMIDIX module through midisim to create MIDI files list
13custom_midi_corpus_file_names = midisim.TMIDIX.create_files_list(['./custom_midi_corpus_dir/'])
14
15# ================================================================================================
16
17# Create two lists: one with MIDI corpus file names
18# and another with MIDI corpus tokens representations suitable for embeddings generation
19midi_corpus_file_names = []
20midi_corpus_tokens = []
21
22for midi_file in tqdm.tqdm(custom_midi_corpus_file_names):
23 midi_corpus_file_names.append(os.path.splitext(os.path.basename(midi_file))[0])
24
25 midi_tokens = midisim.midi_to_tokens(midi_file, transpose_factor=0, verbose=False)[0]
26 midi_corpus_tokens.append(midi_tokens)
27
28# It is highly recommended to sort the resulting corpus by tokens sequence length
29# This greatly speeds up embeddings calculations
30sorted_midi_corpus = sorted(zip(midi_corpus_file_names, midi_corpus_tokens), key=lambda x: len(x[1]))
31midi_corpus_file_names, midi_corpus_tokens = map(list, zip(*sorted_midi_corpus))
32
33# ================================================================================================
34# Now you are ready to generate embeddings as follows:
35# ================================================================================================
36
37# Load main midisim model
38model, ctx, dtype = midisim.load_model(verbose=False)
39
40# Generate MIDI corpus embeddings
41midi_corpus_embeddings = midisim.get_embeddings_bf16(model, midi_corpus_tokens, verbose=False)
42
43# ================================================================================================
44
45# Save generated MIDI corpus embeddings and MIDI corpus file names in one handy NumPy file
46midisim.save_embeddings(midi_corpus_file_names,
47 midi_corpus_embeddings,
48 verbose=False
49 )
50
51# ================================================================================================
52
53# You now can use this saved custom MIDI corpus NumPy file with midisim.load_embeddings()
54# and the rest of the pipeline outlined in the general use section above!pip install -U midisim!pip install -U discovermidi1import discovermidi
2from discovermidi import fast_parallel_extract
3
4discovermidi.download_dataset()
5
6fast_parallel_extract.fast_parallel_extract()1model_ckpt = 'midisim_small_pre_trained_model_2_epochs_43117_steps_0.3148_loss_0.9229_acc.pth'
2model_depth = 8
3
4embeddings_file = 'discover_midi_dataset_3480123_clean_midis_embeddings_cc_by_nc_sa.npy'1model_ckpt = 'midisim_large_pre_trained_model_2_epochs_86275_steps_0.2054_loss_0.9385_acc.pth'
2model_depth = 16
3
4embeddings_file = 'discover_midi_dataset_3480123_clean_midis_embeddings_large_cc_by_nc_sa.npy'1import os
2
3os.makedirs('./Master-MIDI-Dataset/', exist_ok=True)1# Import main midisim module
2import midisim
3
4# Download embeddings from Hugging Face
5emb_path = midisim.download_embeddings(filename=embeddings_file)
6
7# Load downloaded embeddings corpus
8corpus_midi_names, corpus_emb = midisim.load_embeddings(embeddings_path=emb_path)
9
10# Download midisim model from Hugging Face
11model_path = midisim.download_model(filename=model_ckpt)
12
13# Load midisim model
14model, ctx, dtype = midisim.load_model(model_path,
15 depth=model_depth
16 )filez = midisim.TMIDIX.create_files_list(['./Master-MIDI-Dataset/'])1import os
2import tqdm
3
4for fa in tqdm.tqdm(filez):
5
6 # Load source MIDI
7 input_toks_seqs = midisim.midi_to_tokens(fa, verbose=False)
8
9 if input_toks_seqs:
10
11 # ================================================================================================
12 # Calculate and analyze embeddings
13 # ================================================================================================
14
15 # Compute source/query embeddings
16 query_emb = midisim.get_embeddings_bf16(model,
17 input_toks_seqs,
18 verbose=False,
19 show_progress_bar=False
20 )
21
22 # Calculate cosine similarity between source/query MIDI embeddings and embeddings corpus
23 idxs, sims = midisim.cosine_similarity_topk(query_emb,
24 corpus_emb,
25 verbose=False
26 )
27
28 # ================================================================================================
29 # Processs, print and save results
30 # ================================================================================================
31
32 # Convert the results to sorted list with transpose values
33 idxs_sims_tvs_list = midisim.idxs_sims_to_sorted_list(idxs, sims)
34
35 # Print corpus matches (and optionally) convert the final result to a handy list for further processing
36 corpus_matches_list = midisim.print_sorted_idxs_sims_list(idxs_sims_tvs_list,
37 corpus_midi_names,
38 return_as_list=True
39 )
40
41 # ================================================================================================
42 # Copy matched MIDIs from the MIDI corpus for listening and further evaluation and analysis
43 # ================================================================================================
44
45 # Copy matched corpus MIDI to a desired directory for easy evaluation and analysis
46 out_dir_path = midisim.copy_corpus_files(corpus_matches_list,
47 corpus_midis_dirs=['./Discover-MIDI-Dataset/MIDIs/'],
48 main_output_dir='Output-MIDI-Dataset',
49 sub_output_dir=os.path.splitext(os.path.basename(fa))[0],
50 verbose=False
51 )
52 # ================================================================================================midisim.copy_corpus_files — Copy or synchronize MIDI corpus files from a source directory to a target corpus location.midisim.cosine_similarity_topk — Compute cosine similarities between a query embedding and a set of embeddings and return the top‑K matches.midisim.download_all_embeddings — Download an entire embeddings dataset snapshot from a Hugging Face dataset repository to a local directory.midisim.download_embeddings — Download a single precomputed embeddings .npy file from a Hugging Face dataset repository.midisim.download_model — Download a pre-trained model checkpoint file from a Hugging Face model repository to a local directory.midisim.get_embeddings_bf16 — Load or convert embeddings into bfloat16 format for memory-efficient inference on supported hardware.midisim.idxs_sims_to_sorted_list — Convert parallel index and similarity arrays into a single sorted list of (index, similarity) pairs ordered by similarity.midisim.load_embeddings — Load a saved NumPy embeddings file and return the arrays of MIDI names and corresponding embedding vectors.midisim.load_model — Construct a Transformer model, load weights from a checkpoint, move it to the requested device, and return the model with an AMP autocast context and dtype.midisim.masked_mean_pool — Compute a masked mean pooling over sequence embeddings, ignoring padded positions via a boolean or numeric mask.midisim.midi_to_tokens — Convert a single-track MIDI file into one or more compact integer token sequences (with optional transpositions) suitable for model input.midisim.pad_and_mask — Pad a batch of variable-length token sequences to a common length and produce an attention/mask tensor indicating real tokens vs padding.midisim.print_sorted_idxs_sims_list — Pretty-print a sorted list of (index, similarity) pairs, optionally annotating entries with filenames or metadata.midisim.save_embeddings — Save a list of name strings and their corresponding embedding vectors into a structured NumPy array and optionally persist it to disk.midisim.helpers.get_package_models — Return a sorted list of packaged model files and their paths.midisim.helpers.get_package_embeddings — Return a sorted list of packaged embedding files and their paths.midisim.helpers.get_normalized_midi_md5_hash — Compute original and normalized MD5 hashes for a MIDI file.midisim.helpers.normalize_midi_file — Normalize a MIDI file and write the result to disk.midisim.helpers.install_apt_package — Idempotently install an apt package with retries and optional python‑apt.1@misc{project_los_angeles_2025,
2 author = { Project Los Angeles },
3 title = { midisim (Revision 707e311) },
4 year = 2025,
5 url = { https://huggingface.co/projectlosangeles/midisim },
6 doi = { 10.57967/hf/7383 },
7 publisher = { Hugging Face }
8}1@misc{project_los_angeles_2025,
2 author = { Project Los Angeles },
3 title = { midisim-embeddings (Revision 8ebb453) },
4 year = 2025,
5 url = { https://huggingface.co/datasets/projectlosangeles/midisim-embeddings },
6 doi = { 10.57967/hf/7382 },
7 publisher = { Hugging Face }
8}1@misc{project_los_angeles_2025,
2 author = { Project Los Angeles },
3 title = { midisim-samples (Revision 79afcc1) },
4 year = 2025,
5 url = { https://huggingface.co/datasets/projectlosangeles/midisim-samples },
6 doi = { 10.57967/hf/7388 },
7 publisher = { Hugging Face }
8}1@misc{project_los_angeles_2025,
2 author = { Project Los Angeles },
3 title = { Discover-MIDI-Dataset (Revision 0eaecb5) },
4 year = 2025,
5 url = { https://huggingface.co/datasets/projectlosangeles/Discover-MIDI-Dataset },
6 doi = { 10.57967/hf/7361 },
7 publisher = { Hugging Face }
8}