Text Generation
Safetensors
GGUF
qwen3
midi
melody

Info

This is a pretrained transformer autoregressive model, built on the Qwen3 architecture. It is trained to predict sequences of notes each having a pitch, volume, length and starting time. These sequences is written in text and the model predict individual characters.

A note in this format consists of about 7 letters and the model has a maximum sequence length of 8192 letters.

This format does not include the instrument, so we will play the sequences of notes on a piano. The model was trained 20 epochs on Monster-midi dataset containing over 400 000 midi files.

67mval

The following generation was made using:

  • Top_p = 1.0
  • Temperature = 1.0
  • Top_k = None In other, the tokens and thereby notes were sample from pure distribution. In this setting the model is most creative but can sometimes lead to the song going off-track.

The model got as input the first 30 seconds of each song(represents 30 lines in the format) and generated until the models context was full, this sometimes leads to the song being cut in the middle.

Prompt Generation
Alla turca
Axel F
Let it go
Fur Elise
Gimme gimme
Flohwalzer
He's a pirate
River Flows In You
Brainiac Maniac
Stereo Madness
Twinkle Twinkle
Undertale

Remix samples

It is possible to calculate the model's average neurons(it has 32768 neurons in total) activation trough a sequence. We can calculate the average value for each neuron in an existing melody for the first 8192 tokens or the melody's length and then generate a new melody from scratch that steers towards this activation.

This gives us a melody having similar activations to that of the original song, and it tends to sound similar too. In other words, altough the model were never explicitly trained to do this, it seems to be possible to make "remixes" of existing melodies.

What it does a little more specific, is to generate multiple samples in parallell using the model, starting with an empty prompt("*\n"). We then make N independent samples with T tokens each, and inspect the average activation for every neuron in each of the samples. We keep the sample having the most similar activations to the target activation(calculated with cosine similarity). We then keep generating samples from this point and for each new selection the cosine similarity tends to increase. We repeat this R times until the models context is full.

As an example, here is the cosine similarity to pirates of the carabean activations after R number of samples/selections Figure_1 Note that we never alter or change the actual activations in the model, the model does neither has access to any context of the original melody. The only thing that is done is a selection of naturally generated samples.

An interesting thing we can do is to take the average neurons activations of two or multiple melodies and steer towards that to get a kind of mix. The following samples are not cherry picked, only generated once, so quality can vary. The code for this is at the end of this repo.

Melody Remix Final Similarity
Alla turca 0.687
Let it go 0.872
Fur Elise 0.689
Gimme gimme 0.697
Flohwalzer 0.696
He's a pirate 0.787
River Flows In You 0.596
Twinkle Twinkle 0.694
Undertale 0.843
Let it go + AxelF 0.682
GimmeGimme + FurElise 0.556
Let it go + He's a pirate 0.743
Let it go + He's a pirate + Alla turca + Fur Elise 0.541

Quick start

The model needs an initial context to make predictions, to make predictions from melodies from scratch we can use the start "*" as a prompt which is the separator of melodies in the dataset.

from transformers import Qwen3ForCausalLM
import torch

device = "cuda" if torch.cuda.is_available() else "cpu"
model = Qwen3ForCausalLM.from_pretrained("qwrt/Melodimodell-67M").to(device)

prompt="""*"""
gen_len=8192-len(prompt)
print("börjar genereringen")
seed = torch.tensor(list(prompt.encode()), dtype=torch.long)[None].to(device)
out = model.generate(seed, max_new_tokens=gen_len,
                                     do_sample=True, temperature=0.8, top_p=1.0)
text_formated_midi=bytes(out[0].tolist()).decode("utf-8", errors="replace")
print(text_formated_midi)

output

5C5f22 4F4e23 3A3e24 4A3e24 3C2f26
4A5e14 3F4c15 4F3d16 4C3e17 4G5e48 3H4e49 4F5e49 2G5f49
4D6e28 3G4e29 2H4e30
3H5e5 4F6e6 3C4f7 3D4e7 3G4f48 4E6e48
...

To convert the generated string to a playable midi file, we start by installing mido:

!pip install mido

Then, use this script for conversion.

import mido
from huggingface_hub import hf_hub_download


file_path = hf_hub_download(
    repo_id="qwrt/Monster_textmidis_filtered",
    filename="stringtomidi.py",
    repo_type="dataset"
)


spec = importlib.util.spec_from_file_location("parse_custom",file_path)
modul = importlib.util.module_from_spec(spec)
spec.loader.exec_module(modul)

text_formated_midi=text_formated_midi.strip("*") #Remove the first star so to not get an empty string
generated_songs=text_formated_midi.split("*")
first_song=generated_songs[0]

if(len(generated_songs)==1): #remove the last incomplete note of an unfinished melody
    all_notes=first_song.split(" ")
    all_notes.pop()
    first_song=" ".join(all_notes)

events = modul.parse_custom(first_song)
modul.build_midi(events, "example.mid")

You can then use an online tool to convert this midi to a playable mp3 file. Here, the website https://www.freeconvert.com/midi-to-mp3 was used.

Using GGUF in Llama.cpp

Sampling from the model in llama.cpp yields a significant speedup, up to 10x.

1. Install llama.cpp

Follow the instructions at https://github.com/ggml-org/llama.cpp, or install via Homebrew (macOS/Linux):

brew install llama.cpp

2. Download the model

Using the Hugging Face CLI (install with pip install -U huggingface_hub):

hf download qwrt/Melodimodell-67M midi-67m-f16.gguf --local-dir .

Or using curl:

curl -L -o midi-67m-f16.gguf https://huggingface.co/qwrt/Melodimodell-67M/resolve/main/midi-67m-f16.gguf

3. Start the server

llama-server -m midi-67m-f16.gguf -c 8192 --port 8080

Alternatively, skip step 2 and let llama-server download the model for you:

llama-server --hf-repo qwrt/Melodimodell-67M --hf-file midi-67m-f16.gguf -c 8192 --port 8080

4. Sample from the model

The model is byte-level, so the prompt is sent as a list of byte values (token IDs) rather than as a string. Requires pip install requests.

import requests

text = """*
4D4d0 4D4c18 4D4d27 4D4c45 4D4d54
4D4c12 4D4c21 4D4c30 4D4c39 4D4d48
4D4c6 4D4d15 4D4c33 4D4d42 4D4c59
4D4c9 4D4c18 4D4c27 4D4d36 2D4f36 1D4f36 4D4c54
4D4d3 4D4c21 4D4d30 4H4d30 2D4d30 1D4d30 4D4c48 4D4c57 4A4d57 2D4d57 1D4d57
3A4c6 4A4d10 4C4c15 4D4d24 3A4d24 3F4d24 3D4d24 2D4d24 4D4d42 3A4d42 3F4d42 3D4c42 2D4c42 3D4d51 2D4d51 4D4c59 3A4c59 3F4c59
4E4c9 4C4c9 3A4c9 3C4c9 2C4c9 4F4d18 4D4d18 3H4d18 2H4d18 1H4d18 4F4d36 4D4d36 3H4d36 2H4c36 1H4c36 2H4d45 1H4d45 4F4c54 4D4c54 3H4c54
4G4c3 4D4c3 2H4c3 1H4c3 4E4d12 4C4d12 3A4d12 2A4d12 1A4d12 4E4d30 4C4d30 3A4d30 2A4c30 1A4c30 2A4d39 1A4d39 4D4c48 3A4c48 4C4c57 3G4c57 2A4c57 1A4c57
4C4c6 3A4c6 3D4d6 2D4d6 4D4d15 3A4d15 3D4c24 2D4c24 3D4d33 2D4d33 3A4c42 4C4c51 3D4c51 2D4c51
4D4d0 3H4d0 3F4d0 2H4d0 1H4d0 4D4d18 3H4d18 3F4d18 2H4c18 1H4c18 2H4d27 1H4d27 4D4c36 3H4c36 4E4c45 3H4c45 2H4c45 1H4c45 4F4d54 4C4d54 3A4d54 2H4d54 1H4d54
4F4d12 4C4d12 3A4d12 2H4c12 1H4c12 2H4d21 1H4d21 4F4c30 4C4c30 4G4c39 4C4c39 2H4c39 1H4c39 4E4d48 4C4d48 3A4d48 2A4d48 1A4d48
4E4d6 4C4d6 3A4d6 2A4c6 1A4c6 2A4d15 1A4d15 4D4c24 3A4c24 4C4c33 3G4c33 2A4c33 1A4c33 4D4d42 3A4d42 3F4d42 3D4d42 2D4d42 3D4c59 2D4c59
3D4d9 2D4d9 3A4c18 4C4c27 3D4c27 2D4c27 4D4d36 3A4d36 3F4d36 3D4d36 2D4d36 4D4d54 3A4d54 3F4d54 3D4c54 2D4c54
3D4d3 2D4d3 4D4c12 3A4c12 4F4c21 3A4c21 3D4c21 2D4c21 4G4d30 4D4d30 3H4d30 2H4d30 1H4d30 4G4d48 4D4d48 3H4d48 2H4c48 1H4c48 2H4d57 1H4d57
4G4c6 4D4c6 4A4c15 4D4c15 2H4c15 1H4c15 4H4d24 4G4d24 4D4d24 2G4d24 1G4d24 4H4d42 4G4d42 4D4d42 2G4c42 1G4c42 2G4d51 1G4d51 4A4c59 4F4c59
4G4c9 4E4c9 2G4c9 1G4c9 4A4c18 4F4c18 3D4d18 2D4d18 4D4d27 3D4c36 2D4c36 3D4d45 2D4d45 4D4c54"""

r = requests.post("http://localhost:8080/completion", json={
    "prompt": list(text.encode()),  # one token per byte
    "n_predict": 8192 - len(text),
    "temperature": 0.9,
    "top_k": 0, "top_p": 1.0, "min_p": 0.0,
    "repeat_penalty": 1.0,
})
print(text + r.json()["content"])

More Samples

Here are some non-cherry-picked generation using different melodies as a prompt. 30s initial context, temperature=0.9 and Seed=4 for all. Higher temperatures often yields more creative songs since it often increases probabilities for the song to take "new paths". Again the generation is cut after the models maximum context, ensuring that the model can see the whole melody at every position:

Prompt Generation
Alla turca
Dancing queen*
Let it go
Fur Elise
Gimme gimme
Johansson
Pirates of the caribean
Undertale
Stereo Madness

Non cherry picked examples. All generation uses 30 seconds of initial context of each melody and samples are made with:

  • Temperature: 0.8
  • Top p: 1.0
  • Seed = 4
  • Other parameters are set as default

The model sampled until 8192 tokens were reached, some generations contain multiple melodies("*" replaced with pause), and some seem to be able to continue for longer.

Prompt Generation
Alla turca
Dancing queen*
Let it go
Gimme gimme
Fur Elise
Johansson
Pirates of the caribean
Undertale
Stereo Madness

*This melody exceeds 25 notes/second, predictions can be worse.

Remix samplecode

import json, math, os, random, threading, time, traceback, torch, requests
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path

import matplotlib
matplotlib.use("Agg")  # inga fönster som blockerar loopen
from matplotlib import pyplot as plt
from transformers import Qwen3ForCausalLM
from Midimodeller.stringtomidi import parse_custom, build_midi

# Starta servern med N_SLOTS slots och 8192 tokens kontext per slot:
#   llama-server.exe -m Midimodeller/mymodels/version3/67M/midi-67m-f16.gguf -c 131072 -np 16 -ngl 99 --port 8080
# Får du fortfarande minnesfel: -np 8 -c 65536 (och N_SLOTS = 8) ger PyTorch mer VRAM.

SERVER = "http://localhost:8080"
N_SLOTS = 16  # ska matcha -np

# combinations = [
#     ["River"],
#     ["Frozen"],
#     ["alla_turca"],
#     ["FurElise"],
#     ["AxelF"],
#     ["GimmeGimme"],
#     ["Twinkle"],
#     ["kalle"],
#     ["stereo_madness"],
#     ["undertale"],
#     ["piratesoc", "Frozen"],
#     ["River", "FurElise"],
#     ["kalle", "undertale"],
#     ["piratesoc", "Frozen", "FurElise", "alla_turca"],
# ]

combinations = [
    ["FurElise"],
]

CHUNK, START_N, TOTAL = 200, 1024, 8192
MAX_TOKENS = 8192  # tokens per forward pass i acts -> 1 kandidat åt gången i slutet av låten
taljare = 512 * START_N / 8

SAMPLING = dict(
    temperature=1.0, top_p=1.0, top_k=0, min_p=0.0, typical_p=1.0,
    repeat_penalty=1.0, presence_penalty=0.0, frequency_penalty=0.0,
    dry_multiplier=0.0, xtc_probability=0.0,
)

ROOT = Path("../model-docs") / "midimodeller" / "version3" / "67M" / "samples" / "remix_samples"

device = "cuda" if torch.cuda.is_available() else "cpu"
model = Qwen3ForCausalLM.from_pretrained(
    "../Midimodeller/mymodels/version3/67M/bfloat16",
    attn_implementation="sdpa").to(device).eval()
layers = model.model.layers

_local = threading.local()


def session():
    if not hasattr(_local, "s"):
        _local.s = requests.Session()
    return _local.s


def generate_one(prompt_ids, n_new):
    r = session().post(f"{SERVER}/completion", json={
        "prompt": prompt_ids,
        "n_predict": n_new,
        "return_tokens": True,
        "cache_prompt": True,
        "seed": random.randint(0, 2**31 - 1),
        **SAMPLING,
    })
    r.raise_for_status()
    return prompt_ids + r.json()["tokens"]


def is_oom(e):
    return "out of memory" in str(e).lower()


def acts(ids, bs=None):
    """Medelaktivering över hela sekvensen. [batch, seq] -> [batch, lager, d]
    Vid minnesfel: töm cachen och försök igen med halva batchen."""
    if bs is None:
        bs = max(1, MAX_TOKENS // ids.shape[1])
    if ids.shape[0] > bs:
        return torch.cat([acts(ids[i:i + bs], bs) for i in range(0, ids.shape[0], bs)])

    out = {}
    hs = [l.mlp.down_proj.register_forward_hook(
        lambda m, i, o, k=k: out.__setitem__(k, i[0].detach().float().mean(1)))
        for k, l in enumerate(layers)]
    try:
        with torch.no_grad():
            model(input_ids=ids, use_cache=False)
    except Exception as e:
        if not is_oom(e) or ids.shape[0] == 1:
            raise
        out = None
    finally:
        for h in hs:
            h.remove()

    if out is None:
        torch.cuda.empty_cache()
        half = max(1, ids.shape[0] // 2)
        print(f"  (minnesfel, kör om med batch {half})")
        return acts(ids, half)
    return torch.stack([out[k] for k in range(len(layers))], dim=1)


def acts_list(seqs):
    """Batchar bara kandidater med samma längd, så ingen padding behövs."""
    res = [None] * len(seqs)
    by_len = {}
    for i, s in enumerate(seqs):
        by_len.setdefault(len(s), []).append(i)
    for idx in by_len.values():
        a = acts(torch.tensor([seqs[i] for i in idx], dtype=torch.long, device=device))
        for j, i in enumerate(idx):
            res[i] = a[j]
    return torch.stack(res)


def enc(t):
    return torch.tensor(list(t.encode()[:TOTAL]), dtype=torch.long, device=device)[None]


def dec(ids):
    return bytes(t for t in ids if t < 256).decode("utf-8", errors="replace")


raw = json.load(open("../test/Vibecodefun/interpretability/mlp/neuron_activation.json"))
base = torch.tensor([raw[k]["mean_signed"] for k in raw]).float().mean(0).to(device)


def song_dir(name):
    """Normaliserad stilvektor per lager för en låt: [lager, d]"""
    t = acts(enc(open(f"../Midimodeller/evaluation/{name}.txt").read()))[0] - base
    return t / t.norm(dim=-1, keepdim=True)


def run_song(song_names):
    """Kör en kombination. Returnerar True om den blev klar."""
    weights = [1 / len(song_names)] * len(song_names)
    song_name = "+".join(song_names)
    sample_dir = ROOT / song_name
    os.makedirs(sample_dir, exist_ok=True)
    checkpoint_path = sample_dir / f"checkpoint_{CHUNK}_{START_N}.json"
    done_path = sample_dir / f"done_{CHUNK}_{START_N}.txt"

    if done_path.exists():
        print(f"=== {song_name}: redan klar, hoppar över")
        return True
    print(f"=== {song_name}")

    dirs = torch.stack([song_dir(n) for n in song_names])  # [låtar, lager, d]
    w = torch.tensor(weights, device=device)[:, None, None]
    target = (w * dirs).sum(0)
    target = target / target.norm(dim=-1, keepdim=True)

    if checkpoint_path.exists():
        ck = json.load(open(checkpoint_path))
        seq, all_scores = ck["seq"], ck["all_scores"]
        print(f"Fortsätter från checkpoint: {len(seq)} tokens")
    else:
        seq, all_scores = list("*\n".encode()), []

    finished = False
    interrupted = False
    try:
        with ThreadPoolExecutor(N_SLOTS) as pool:
            while len(seq) < TOTAL:
                N_CAND = max(1, math.floor(taljare / (len(seq) + 512)) * 8)
                n_new = min(CHUNK, TOTAL - len(seq))

                kids = list(pool.map(lambda _: generate_one(seq, n_new), range(N_CAND)))

                c = acts_list(kids) - base
                c = c / c.norm(dim=-1, keepdim=True)
                scores = (c * target).sum(-1).mean(-1)

                best = kids[int(scores.argmax())]
                if len(best) == len(seq):
                    break
                seq = best
                all_scores.append(scores.mean().item())

                print(f"{song_name}  {len(seq):5d}  N_CAND {N_CAND:4d}  {scores.max():+.4f}  spridning {scores.std():.5f}")
                json.dump({"seq": seq, "all_scores": all_scores}, open(checkpoint_path, "w"))
                torch.cuda.empty_cache()
        finished = True
    except KeyboardInterrupt:
        interrupted = True
        print(f"\nAvbruten vid {len(seq)} tokens, sparar och stoppar.")
    except Exception:
        traceback.print_exc()
        print(f"\n{song_name} kraschade vid {len(seq)} tokens, sparar det som finns.")

    # Spara resultatet; ett fel här ska inte stoppa resten av kombinationerna
    try:
        final_txt = dec(seq)
        all_notes = final_txt.split(" ")
        all_notes.pop()
        events = parse_custom(" ".join(all_notes))
        date = time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime())
        status = "" if finished else f"-partial{len(seq)}"
        output_path = sample_dir / f"{song_name}({CHUNK},{START_N},v2-gguf-{date}{status})"
        os.makedirs(output_path, exist_ok=True)
        build_midi(events, f"{output_path}/song.midi")
        json.dump(all_scores, open(f"{output_path}/similarities.json", "w"))

        plt.figure()
        plt.plot(all_scores)
        plt.title(song_name)
        plt.savefig(f"{output_path}/similarities.png")
        plt.close()
    except Exception:
        traceback.print_exc()
        print(f"Kunde inte spara {song_name}.")

    if finished:
        checkpoint_path.unlink(missing_ok=True)
        done_path.write_text(date)
    if interrupted:
        raise KeyboardInterrupt
    return finished


try:
    results = {}
    for song_names in combinations:
        results["+".join(song_names)] = run_song(song_names)
        torch.cuda.empty_cache()
except KeyboardInterrupt:
    print("Hela körningen avbruten. Kör skriptet igen för att fortsätta där det slutade.")
else:
    print("\nSammanfattning:")
    for name, ok in results.items():
        print(f"  {'klar   ' if ok else 'EJ KLAR'}  {name}")
Downloads last month
203
Safetensors
Model size
67.4M params
Tensor type
BF16
·
Inference Providers NEW
This model isn't deployed by any Inference Provider. 🙋 Ask for provider support

Dataset used to train qwrt/Melodimodell-67M

Space using qwrt/Melodimodell-67M 1