TuneLM: Finetuning LLMs to Compose Music through Code

TuneLM finetunes LiquidAI's LFM3-1.7B model to compose executable Strudel music programs through SFT and GRPO stages.

18 min readShanmukha Sainath
HeaderAn illustration of TuneLM

Introduction

Measuring Human and AI Capabilities

There are many frameworks used to measure human capabilities across various dimensions such as creativity, intelligence, reasoning, social dynamics, and organizational skills. But for AI, most of these metrics are not applicable atleast not until now.

Human capabilities frameworkHuman capabilities framework

Recent Developments in LLMs

Since the rise of modern LLMs in 2022, there have been tremendous improvements. LLMs have evolved from simple chatbots to disrupting nearly every industry imaginable. As models grew more capable, evaluation benchmarks began capturing diverse competencies—including coding, problem-solving, mathematics, biology, and chemistry. We have even reached a point where solving centuries-old open problems has become commonplace for frontier models like Fable, Astra, and Gemini 4 Carbon.

An overview of the different tasks LLMs were tested on over the yearsAn overview of the different tasks LLMs were tested on over the years

There is a nice article from Anthropic on the Economic Impacts of AI.

All of these evaluations fall under the umbrella of Intelligence Quotient (IQ). Recently, there has been a heavy push to make LLMs more creative. Notable demonstrations include:

This highlights an exciting transition from Intelligence Quotient (IQ) to Creative Quotient (CQ). Unlike IQ, creativity is difficult to quantify, but this is only the beginning and we will likely see even more remarkable demonstrations in the future.

Emotional Quotient will probably come into the picture when we achieve AGI :p

LLMs Evaluation TrendAn illustration of the evolution of LLM evaluation benchmarks

Strudel - The Language of Music Composition

Strudel is a port of Tidal Cycles written in JavaScript. TidalCycles is a language designed for algorithmic patterns, most commonly used for musical composition. Its widely used for live-coding music, algorithmic composition, and teaching music and programming simultaneously.

Strudel editor

Why Am I Building This?

I came across Strudel when it was played during the Cursor Roadshow in Bangalore on August 1st. I was fascinated by the fact that a small code snippet was generating music in real time, and it felt genuinely magical.

Cursor Roadshow BangaloreCursor Roadshow Bangalore

BrushArena, developed by @kickingkeys, is a great example of code generating images using the p5.js library. He even fine-tuned a Qwen-2.5 27B model to write p5.js code for generating artwork. Check out his blog post for more details.

This project inspired me to explore other modalities and decided to try with audio (specifically music), and after considerable research looking for code to music libraries/frameworks, I returned to generating music with Strudel. Luckily, the timing worked out with cursor rodshow otherwise I would have probably forgot about Strudel. I tried generating Strudel code with many powerful LLMs (ChatGPT, Claude, Gemini, DeepSeek, Kimi...) and realized that most of them cannot produce functional Strudel code that plays music aligning with description. At the time of writing, Gemini 4 Carbon seems to be the best at it (with Astra and Fable close behind). This gave me confidence that fine-tuning Small Language Models (SLMs) would be an ideal project, and that Strudel code generation could serve as an excellent benchmark for evaluating an LLM's Creativity Quotient (CQ).

Dataset Preparation

Stem Database

Even though LLMs are not explicitly pre-trained on Strudel (my guess), they can still write Strudel code if they understand how to represent sounds, notes, and effects in the language. So I first decided to create a corpus of these musical components alongside descriptions using publicly available Strudel examples. A composition is a full Strudel program, while a stem is an independently playable part extracted from it—such as a drum pattern, chord progression, or bass line. We used the JavaScript parser Acorn to extract stems from all collected compositions. Unfortunately there are not many publicly available Strudel examples, but here are the top sources I could find:

Top sources of verified stems
Stems of a sample Strudel codeStems of a sample Strudel code

Each stem receives a description (either extracted from the original corpus or generated by an LLM). These descriptions are converted into embeddings using sentence-transformers to build a RAG database, which can later retrieve relevant stems for a given prompt.

Finding Relevant Stems

Now that we have a database, we need a metric to retrieve relevant stems. Cosine similarity between the embeddings of the query and the stem descriptions is a straightforward option, but most descriptions were not sufficiently detailed, and manually annotating them was challenging given my lack of formal music background. After testing, I incorporated two additional criteria derived from the plan that the teacher model creates before composing Strudel code:

  • Techniques: These are Strudel methods that alter or govern how a component is played (e.g., slow, fast, rev, lpf, hpf, gain, delay). We compute the overlap between requested techniques and the techniques present in the candidate stem.
  • Structural Variation: We execute the stem over a fixed window (typically 16 cycles). For each cycle, we build a fingerprint from audible event timings, durations, sound IDs, and note or sample indices. Altering a note, adding an onset, or shifting its timing creates a distinct fingerprint. To encourage musical diversity, we give a small positive weight to reference stems that demonstrate progression.
retrieval score=0.65×cosine(query,stem)+0.25×technique overlap+0.10×structural variation\text{retrieval score} = 0.65 \times \text{cosine}(\text{query}, \text{stem}) + 0.25 \times \text{technique overlap} + 0.10 \times \text{structural variation}
Retrieval Score
Retrieval Metrics ExampleRetrieval Metrics Example

I didn't explore this further, as my tests showed little advantage from relying on the stem database.

SFT Pairs

To generate supervised fine-tuning (SFT) pairs, I created musical description prompts and responses separately. Generating both would be ideal but prompts required a lot of human intervention to ensure they are realistic and not repetitive.

Musical Descriptions

To generate diverse musical descriptions, I used several LLMs spanning different providers and model sizes. The system prompt requested varied moods, styles, instrumentations, practical use cases, grooves, and temporal dynamics. It included single parts, layered arrangements, and requests to extend existing code. I supplemented these with human-written descriptions from the Song Describer Dataset, which contains high-quality audio-caption pairs for music-and-language research. In total, 2,500 prompts were curated: 500 from Song Describer and 2,000 generated using LLMs.

One mistake I made early on was generating prompts from scratch before researching existing music datasets. Later, I realized that several open-source datasets and using them could have saved significant time.

Teacher Responses

Each response consists of a structured plan, composition notes, and the final Strudel code. The composition notes provide chain-of-thought reasoning that helps the student model understand the rationale behind specific musical choices, leading to much better learning. This reasoning bridges the gap between the initial prompt requirements and the generated program.

{
  "prompt": "Keep a 60 bpm click with a low sine on the first beat of every bar and a faint tick on the rest for my breathing practice.",
  "summary": "Play a low C2 sine tone on the first beat and a quiet hi-hat tick on beats two, three, and four. Repeat the pattern at 60 BPM.",
  "code": "setcpm(60/4)\n\nconst downbeat_sine = note(\"c2 ~ ~ ~\")\n  .s(\"sine\")\n  .gain(0.45)\n\nconst faint_ticks = s(\"~ hh hh hh\")\n  .gain(0.15)\n\nstack(\n  downbeat_sine,\n  faint_ticks\n)",
  "teacher": "gemini:gemini-4-argon"
}
SFT Sample

RL Prompts and Constraints

We generated reinforcement learning prompts following rules similar to the SFT stage, but with a heavier focus on verifiable constraints. The teacher model produces a machine-checkable request contract used to evaluate how faithfully the generated Strudel code satisfies instructions. Each request must specify at least two checkable constraints, including required or forbidden instruments, part counts, tempo, or musical key.

{
  "prompt": "No drums underneath. Just solo cello, 76 bpm in E minor.",
  "contract": {
    "require": [
      { "family": "cello", "quote": "cello" }
    ],
    "forbid": [
      { "family": "drums", "quote": "No drums" }
    ],
    "voices": { "min": 1, "max": 1, "quote": "solo" },
    "tempo": { "bpm": 76, "quote": "76 bpm" },
    "key": { "key": "E:minor", "quote": "E minor" }
  }
}
RL Sample

SFT - Supervised Finetuning

At the time of this project, Liquid AI's LFM3-1.7B was the top-performing Small Language Model (SLM) in its parameter scale. I recommend reading their announcement blog to understand the architecture and technical details. I chose it for TuneLM considering it's coding capabilities and also finetuning costs.

LoRA fine-tuning was performed with rank 16, alpha 32, and an adapter dropout of 0.05. Below are the training hyperparameters and loss trajectory. The validation loss is reported on 250 held-out SFT samples.

SettingValue
Training / validation rows2,526 / 250
Epochs3
Learning rate0.0002
Per-device train batch / accumulation1 / 8
Warm-up steps25
Precisionbfloat16
Validation interval50 optimizer steps
SFT training parameters
Cross-entropy loss and next-token accuracy during SFT training and validation

GRPO - Group Relative Policy Optimization

To ensure the model strictly adheres to user-requested musical constraints, we used GRPO as the RL method. GRPO evaluates sampled completions against the group mean of completions for the same prompt. A candidate that scores above its group's mean receives a positive advantage, while one below receives a negative advantage. If all samples in a group receive identical rewards, no relative advantage is assigned.

There is a wonderful Hugging Face blog post explaining the key differences between PPO and GRPO.

Reward Function

For the RL stage, the reward function was designed to reflect what the listener actually requested. Each prompt defines measurable criteria, such as including specific instruments, targeting an exact tempo, or omitting specific instruments. We execute the generated Strudel code and evaluate those requirements directly against the scheduled audio events. Instruction following accounts for 80% of the base reward, while the remaining 20% verifies that tempo and key declarations in the composition notes match the executed code. Invalid or unparseable responses receive zero reward. Each failed quality check halves the base score, and a length penalty discourages responses approaching the token budget. This incentivizes executable code and concrete musical compliance while keeping stylistic choices open.

This objective is designed by Gemini-4-Argon based on the requirements I gave.

Reward componentHow we calculate it
Format and execution gate (GG)Set to 1 when the response contains valid composition notes and code, and the program passes execution checks. Otherwise, set to 0.
Instrument requirementsCheck whether requested sound families appear. Each required family has weight 1. Each forbidden family has weight 2, with weight 0.5 for excluding vocals.
Tempo, key, and part countEach has weight 1. Tempo must match within 1 BPM. At least 90% of pitched onsets must fit the requested scale. Part count uses sound IDs and instrument-family grouping.
Structure and densityEach has weight 0.5. Check for a requested build, thinning, or contrast. Sparse music allows at most 8 onsets per cycle, while busy music requires at least 12.
Preserve supplied codeWeight 2. The original code must remain intact, and the resulting program must produce a change in its musical telemetry.
Contract score (CC)Divide the total weight of passed requirements by the total weight of applicable requirements.
Notes agreement (HH)Average the applicable tempo and key checks between the composition notes and executed code. Defaults to 1 when neither claim appears.
Failed quality checks (FF)Count failures involving event density, gain, excessive sound sources, repetition, and scale consistency. Each failure halves the base reward. The checks adapt to explicit loop, key, and part-count requests.
Length penaltyIncrease linearly from 0 to 0.2 between 2,816 and 3,072 completion tokens (LL). Apply this after calculating the base reward.
Reward function components and calculation rules
R=G×0.5F×(0.8C+0.2H)−0.2 clip⁡ ⁣(L−2816256, 0, 1)\boxed{ R = G \times 0.5^{F} \times (0.8C + 0.2H) - 0.2\,\operatorname{clip}\!\left(\frac{L-2816}{256},\,0,\,1\right) }
Reward Function

The best checkpoint in terms of mean reward and code execution accuracy occurred at step 250 (out of 440 total steps in the GRPO stage).

Mean validation reward and execution rate across GRPO training steps

Evaluation

The fine-tuned model must be evaluated not only on code execution but also on musical quality. To measure performance against existing state-of-the-art music generation models, I benchmarked TuneLM across several audio metrics.

For the evaluation set, we selected MusicPrefs due to its standard usage and small data size. This benchmark contains 120 text descriptions and corresponding music outputs from 7 different models.

CLAP

CLAP adapts the contrastive learning approach of CLIP to the audio domain, introduced in the LAION-CLAP paper to evaluate text-audio alignment. A joint audio-language model embeds the prompt and the rendered clip into a shared representation space. The score is computed as the cosine similarity between the audio and text embeddings.

FAD (Fréchet Audio Distance) & FAD-CLAP

Fréchet Audio Distance fits a multivariate Gaussian distribution to generated audio embeddings and compares it against a reference Gaussian. The metric sums the squared distance between mean feature vectors and a covariance trace term. Standard FAD uses VGGish embeddings on audio resampled to 16 kHz, while FAD-CLAP uses LAION-CLAP embeddings at 48 kHz. We use the fixed FMA-Pop reference statistics distributed with FADtk.

FMA-Pop is a curated subset of the Free Music Archive focusing on tracks categorized under pop. It comprises 4,230 excerpts of 30 seconds each, serving as a clean reference collection of recorded human music.

FAD=∥μg−μr∥22+Tr⁡(Σg+Σr−2(Σr1/2ΣgΣr1/2)1/2)\mathrm{FAD} = \left\|\mu_g-\mu_r\right\|_2^2 + \operatorname{Tr}\left( \Sigma_g+\Sigma_r - 2\left( \Sigma_r^{1/2}\Sigma_g\Sigma_r^{1/2} \right)^{1/2} \right)
FAD Formula

Here, gg represents generated audio and rr represents the reference distribution. The vectors μg,μr\mu_g, \mu_r are the mean feature embeddings, and Σg,Σr\Sigma_g, \Sigma_r are the respective covariance matrices. Lower FAD indicates closer alignment with reference audio.

MAD - MAUVE Audio Divergence

MAUVE Audio Divergence resamples audio clips to 24 kHz and extracts layer-24 hidden representations from the MERT-v1-330M model, taking the maximum along each feature dimension across time. This produces a single vector per clip. MAUVE quantizes these features in a shared space and computes divergence frontiers between the empirical distributions. The reported score is −ln⁡(MAUVE)-\ln(\text{MAUVE}) with seed 25, using FMA-Pop as reference audio.

A 10-second evaluation window was selected, covering 114 out of the 120 prompts in the set. Of these, 103 prompts generated valid, executable Strudel code across all tested checkpoints, forming the common comparison subset across all models. We also compare directly against Gemini 4 Argon, which served as our teacher model.

Benchmark comparison of TuneLM (step 250) against dedicated audio generators and Gemini 4 Argon on 103 shared prompts
Trajectory of audio evaluation metrics (CLAP, FAD, FAD-CLAP, and MAD) across TuneLM training checkpoints

Try It Out Yourself

You can explore the interactive demo at tensorwrites.com/tunelm and inspect the code, datasets, and training configurations on GitHub.

TuneLM Demo

Things That Didn't Work

I started this project three months ago with the Gemma 4 E4B model. The early SFT checkpoint quality was not up to the mark, and I lacked confidence in the initial data representation, causing progress to stall until Liquid AI released LFM3-1.7B. The journey since involved several failed experiments and valuable takeaways:

Do Not Over-Restrict the Teacher Model

Initially, I forced the teacher model to compose Strudel programs using only retrieved stems. After listening to hundreds of samples, I noticed that the music sounded unnatural and constrained. Analysis confirmed that strictly relying on retrieved stems limited model's expressivity. Updating the system prompt to make stem usage optional significantly improved the quality and diversity of the teacher's outputs.

Reasoning Matters

My initial trials with Gemma 4 omitted chain-of-thought reasoning from the SFT target outputs, which was likely the primary reason for weak performance. As noted in the SFT section, explicit reasoning context is critical—it helps the model understand musical planning and learn composition logic far more effectively.

Fine-Tuning Is Only as Good as the Data

I spent a substantial amount of time generating SFT prompts. This was crucial because human-authored musical descriptions were scarce. The earliest prompt generations failed to capture natural listener requests, so I iterated through several system prompts, added historical prompts into context to prevent repetitive patterns, and prompted models from multiple providers to maximize prompt diversity.

The Reward Function Is Everything

I consider myself lucky with the reward function design because getting RL reward function right for new domains is crazy difficult and our first itself function worked out very well.

References

  1. Strudel — TidalCycles live-coding environment ported to JavaScript.
  2. Tidal Cycles — Pattern language for algorithmic musical composition.
  3. RL-ing Qwen to Paint with Code — Surya (@kickingkeys) on code generation with P5.js.
  4. Liquid Foundation Models (LFM3) — Liquid AI technical architecture and release.
  5. Hu, E. J. et al. “LoRA: Low-Rank Adaptation of Large Language Models.” ICLR (2022). arXiv:2106.09685.
  6. Shao, Z. et al. “DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models.” arXiv:2402.03300 (2024). arXiv:2402.03300.
  7. Yu, P. et al. “DAPO: Direct Advantage Policy Optimization.” arXiv:2503.14476 (2025). arXiv:2503.14476.
  8. TRL - Group Relative Policy Optimization — Hugging Face TRL documentation.
  9. Difference between PPO and GRPO — NormalUhr (Hugging Face Blog).
  10. Mckee, D. et al. “Song Describer: A Dataset for Grounded Music-and-Language Evaluation.” arXiv:2311.10057 (2023). arXiv:2311.10057.
  11. Pasztor, B. et al. “MusicPrefs: A Dataset of Text-to-Music Model Outputs and Human Preference Ratings.” arXiv:2503.16669 (2025). arXiv:2503.16669.
  12. Wu, Y. et al. “Large-scale Contrastive Language-Audio Pretraining with Feature Fusion and Keyword-to-Caption Augmentation.” ICASSP (2023). arXiv:2211.06687.
  13. Kilgour, K. et al. “Fréchet Audio Distance: A Metric for Evaluating Music Enhancement Algorithms.” Interspeech (2019). arXiv:1812.08466.
  14. Gui, A. et al. “Adapting Fréchet Audio Distance for Generative Music Evaluation.” arXiv:2311.01616 (2023). arXiv:2311.01616.
  15. FADtk (Fréchet Audio Distance Toolkit) — Microsoft Research toolkit for reproducible FAD computation.
  16. Li, Y. et al. “MERT: Acoustic Representation Learning for Music Understanding.” arXiv:2306.00107 (2023). arXiv:2306.00107.
  17. Pillutla, K. et al. “MAUVE: Measuring the Gap Between Neural Text and Human Text using Divergence Frontiers.” NeurIPS (2021). arXiv:2102.01454.

Tools

  • Hardware: NVIDIA RTX 3090 (24GB VRAM)
  • Code Editor: Cursor
  • Algorithm Development: Codex/Cursor
  • Training Logging: Weights & Biases
  • GPU Provider: VastAI
  • Inference Endpoint: Modal

Citation

Cited as:

Shanmukha Sainath. "TuneLM: Finetuning LLMs to Compose Music through Code". TensorWrites (Nov 2026). https://www.tensorwrites.com/posts/tunelm

BibTeX:
@article{tunelm2026,
  title   = "TuneLM: Finetuning LLMs to Compose Music through Code",
  author  = "Shanmukha Sainath",
  journal = "TensorWrites",
  year    = "2026",
  month   = "Nov",
  url     = "https://www.tensorwrites.com/posts/tunelm"
}