Tutorial
Fine-tune a small model with LoRA
Fine-tune a small open model with LoRA using TRL and PEFT, measure it on a held-out set before and after, and decide whether the gain is worth keeping.
Bookmark
Bookmarks are kept in your free account, so you can find this page again on any device.
Sign in to bookmarkOn this page
Fine-tuning changes a model’s weights so it does one job better than prompting alone gets it to. LoRA (low-rank adaptation) does this cheaply: instead of updating billions of parameters, it trains small adapter matrices alongside a frozen base model. The adapter is a few tens of megabytes, trains on one GPU, and can be swapped in and out.
This tutorial fine-tunes Qwen3-0.6B to turn customer emails into a fixed JSON record. The method matters more than the task: build a held-out eval first, score the base model, train, score again, and only keep the adapter if the numbers justify it. Written against TRL 1.18 and PEFT 0.22 on 20 November 2026.
Should you fine-tune at all?
Usually not first. Try these in order and measure each:
- A clear prompt with a schema and three good examples.
- Structured outputs, so the format is enforced rather than hoped for.
- A larger model, if the small one is not good enough.
- Retrieval, if the problem is missing knowledge rather than behaviour.
Fine-tuning is worth it when a small model must do a narrow, repetitive task cheaply or offline, when you have hundreds or thousands of real examples, and when prompting a small model plateaus below what you need. It is a poor way to add facts that change; use RAG for that. RAG vs long context vs fine-tuning goes through the decision.
1. Prepare the data
Use the conversational format TRL expects: one JSON object per line with a messages list. Keep the system prompt identical in training and at inference.
{"messages": [{"role": "system", "content": "Extract the order record from the email. Reply with JSON only: {\"order_id\": string|null, \"intent\": \"refund\"|\"exchange\"|\"status\"|\"other\", \"items\": [string]}"}, {"role": "user", "content": "Hi, order 88-1204 came with the wrong mug, can I swap it for the blue one?"}, {"role": "assistant", "content": "{\"order_id\": \"88-1204\", \"intent\": \"exchange\", \"items\": [\"mug\"]}"}]}
Split before you do anything else, and never look at the test file while iterating:
# split.py
import json
import random
rows = [json.loads(line) for line in open("all.jsonl", encoding="utf-8")]
random.Random(42).shuffle(rows)
cut = int(len(rows) * 0.85)
for name, part in [("train.jsonl", rows[:cut]), ("test.jsonl", rows[cut:])]:
with open(name, "w", encoding="utf-8") as f:
f.writelines(json.dumps(r) + "\n" for r in part)
print(f"train={cut} test={len(rows) - cut}")
Check the data by hand before training. Read fifty examples. Inconsistent labels in training data become inconsistent behaviour in the model, and no hyperparameter fixes that.
2. Install
python -m venv .venv && source .venv/bin/activate
pip install "trl>=1.18" "peft>=0.22" "datasets>=5" accelerate
3. Score the base model first
The baseline is what you are trying to beat. Create evaluate.py:
# evaluate.py
import json
import sys
import torch
from peft import PeftModel
from transformers import AutoModelForCausalLM, AutoTokenizer
BASE = "Qwen/Qwen3-0.6B"
def load(adapter: str | None):
tok = AutoTokenizer.from_pretrained(BASE)
model = AutoModelForCausalLM.from_pretrained(BASE, dtype=torch.bfloat16, device_map="auto")
if adapter:
model = PeftModel.from_pretrained(model, adapter)
return tok, model.eval()
def generate(tok, model, messages) -> str:
prompt = tok.apply_chat_template(
messages, add_generation_prompt=True, tokenize=False, enable_thinking=False
)
inputs = tok(prompt, return_tensors="pt").to(model.device)
with torch.no_grad():
out = model.generate(**inputs, max_new_tokens=200, do_sample=False)
return tok.decode(out[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True).strip()
def score(pred: str, gold: str) -> dict:
try:
p = json.loads(pred)
except json.JSONDecodeError:
return {"valid": 0, "exact": 0, "order_id": 0, "intent": 0}
g = json.loads(gold)
return {
"valid": 1,
"exact": int(p == g),
"order_id": int(p.get("order_id") == g["order_id"]),
"intent": int(p.get("intent") == g["intent"]),
}
if __name__ == "__main__":
adapter = sys.argv[1] if len(sys.argv) > 1 else None
tok, model = load(adapter)
rows = [json.loads(line) for line in open("test.jsonl", encoding="utf-8")]
totals = {"valid": 0, "exact": 0, "order_id": 0, "intent": 0}
for row in rows:
prompt, gold = row["messages"][:-1], row["messages"][-1]["content"]
for k, v in score(generate(tok, model, prompt), gold).items():
totals[k] += v
print(adapter or "base", {k: round(v / len(rows), 3) for k, v in totals.items()})
Run it on the base model:
python evaluate.py
Write the numbers down. Per-field accuracy (order_id, intent) tells you more than exact match, because it shows which part of the task is hard. Also score the prompt-only alternatives from the list above on the same test set, so the comparison is fair.
4. Train the adapter
Create train.py:
# train.py
import torch
from datasets import load_dataset
from peft import LoraConfig
from trl import SFTConfig, SFTTrainer
train = load_dataset("json", data_files="train.jsonl", split="train")
trainer = SFTTrainer(
model="Qwen/Qwen3-0.6B",
train_dataset=train,
args=SFTConfig(
output_dir="qwen3-0.6b-orders-lora",
num_train_epochs=3,
learning_rate=1e-4,
per_device_train_batch_size=8,
max_length=1024,
assistant_only_loss=True,
model_init_kwargs={"dtype": torch.bfloat16},
logging_steps=10,
save_strategy="epoch",
report_to="none",
),
peft_config=LoraConfig(
r=16,
lora_alpha=32,
lora_dropout=0.05,
target_modules="all-linear",
task_type="CAUSAL_LM",
),
)
trainer.train()
trainer.save_model()
The settings that matter:
peft_configturns this into LoRA training. Only the adapter weights are trained; the 0.6B base stays frozen.r=16is the adapter rank, the size of the low-rank matrices. Higher rank can learn more and overfit sooner. 8 to 32 is a common range for narrow tasks.target_modules="all-linear"puts adapters on every linear layer, which generally works better than attention-only adapters.learning_rate=1e-4: adapters train with a higher rate than full fine-tuning, as TRL’s documentation notes.assistant_only_loss=Truecomputes the loss only on the assistant’s JSON, not on the email or system prompt. You want the model to learn to answer, not to write emails. TRL patches the chat template for known families such as Qwen3 to support this.model_init_kwargs={"dtype": torch.bfloat16}loads the base in bfloat16. Without it, TRL loads in float32 and uses twice the memory.
python train.py
Watch the training loss. It should fall steadily and flatten. If it drops to near zero within the first epoch on a few hundred examples, the model is memorising; reduce epochs or rank.
5. Score again, on the same test set
python evaluate.py qwen3-0.6b-orders-lora
Now compare the two lines. Decide in advance what counts as worth it. For example: “exact match up by at least 10 points, valid JSON at 100%, and no field worse than the base.” If the adapter does not clear the bar, do not ship it. That is a result, not a failure.
Then check what you might have broken. Fine-tuning on one task can make the model worse at others. If the model serves anything else, run a few general prompts through base and adapter and read the answers side by side.
6. Use the adapter
For serving with Transformers, load the base and attach the adapter, exactly as evaluate.py does. To serve with vLLM or llama.cpp, or to run it in Ollama, merge the adapter into the base weights first:
from peft import PeftModel
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch
base = AutoModelForCausalLM.from_pretrained("Qwen/Qwen3-0.6B", dtype=torch.bfloat16)
merged = PeftModel.from_pretrained(base, "qwen3-0.6b-orders-lora").merge_and_unload()
merged.save_pretrained("qwen3-0.6b-orders-merged")
AutoTokenizer.from_pretrained("Qwen/Qwen3-0.6B").save_pretrained("qwen3-0.6b-orders-merged")
Check the base model’s licence before you distribute merged weights.
When it is not worth it
Be honest about these outcomes:
- The gain is small. A few points on a 100-example test set can be noise. Bootstrap the test set or collect more examples before trusting it.
- A bigger model with a good prompt matches it. Then you are trading engineering time and an extra model to maintain for a lower per-request price. Do the arithmetic at your real volume.
- The task drifts. If the schema or categories change monthly, you will be retraining monthly. Prompts change in minutes.
Pitfalls
Evaluating on training data. The single most common mistake. Split first, and keep the test set out of every step until scoring.
Different prompts at train and test time. The adapter learns the exact system prompt and chat template. Change either and results fall.
Too little data, too many epochs. A few hundred examples and ten epochs gives a model that recites its training set.
Leaking personal data. Training data ends up in the weights. Remove personal data from examples, and treat the adapter as sensitive if you could not.
Next steps
- Run the merged model locally with Ollama.
- Review the decision in RAG vs long context vs fine-tuning.
- For more depth on post-training methods, Hugging Face’s smol course covers instruction tuning, preference alignment and evaluation.
- Check whether prompting with a schema already gets you there in get JSON from an LLM with structured outputs.
- Build the held-out set properly with write your first LLM eval.
- See where this fits with local inference in the fine-tuning and local models learning path.
Covers
Check your understanding
Fine-tune a small model with LoRA quiz
When to fine-tune, data splits and checks, scoring the base model first, LoRA settings in TRL, judging an adapter against a bar set in advance, merging and common pitfalls.
8 questions · pass mark 70%
Review
Related
- RAG vs long context vs fine-tuning: how to choose
What each approach changes, what it costs, where it fails, and a practical order to try them in before you commit to one.
- Run local models with Ollama
Install Ollama, run an open-weight model on your own machine, call it from scripts over the local API and choose a model size your hardware can handle, offline.
- Write your first LLM eval
Turn real outputs into a small test set, add code-based checks in promptfoo and run them in CI to catch regressions on every change.
- LoRA
Low-Rank Adaptation: a fine-tuning method that freezes the model's weights and trains small added matrices instead, cutting memory needs.
- Supervised fine-tuning (SFT)
Fine-tuning on labelled input and output pairs so the model learns to produce the target output for each input.