Level 2 Agentic Coding · Building with AI
Fine-Tuning an Open Model in Practice
A step-by-step QLoRA fine-tune of a small open model with Hugging Face transformers, PEFT and TRL. It covers deciding whether to fine-tune at all, formatting the data, choosing hyperparameters, watching training, evaluating against the base model, and merging the adapter for deployment.
- Level
- ●●●●● Intermediate
- Reading
- 14 min
- To learn it well
- 2 hours to read, a day for a first fine-tune on a rented or free GPU
- Builds on
- 47 concepts →
- Quiz
- 5 questions ↓
This leads to
—The full path from zero — 47 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- Python for AI
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- The Chain Rule
- Dot Product, Norms and Similarity
- Tokenization
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Tensors and Shapes
- Eigenvectors and SVD
- NumPy and Array Thinking
- Language Modeling and Next-Token Prediction
- Supervised Learning
- Linear Regression
- Training, Validation and Test Sets
- The Perceptron
- Logistic Regression
- Overfitting and the Bias–Variance Tradeoff
- Regularization: L1 and L2
- Neural Networks
- Recurrent Neural Networks
- Backpropagation
- Activation Functions
- Dropout and Regularizing Neural Networks
- PyTorch
- Vanishing and Exploding Gradients
- Normalization Layers: BatchNorm and LayerNorm
- Optimizers: SGD, Momentum and Adam
- LSTMs and GRUs
- Residual Connections
- Training Neural Networks in Practice
- Sequence-to-Sequence Models
- Transfer Learning
- Attention
- Self-Attention and Multi-Head Attention
- Positional Encodings
- The Transformer
- The Hugging Face Ecosystem
- GPT and Decoder-Only Models
- Pretraining Large Language Models
- Fine-Tuning
- LoRA and Parameter-Efficient Fine-Tuning
- Fine-Tuning an Open Model in Practice
Read them roughly in this order. See it on the concept map →
Why it matters
The Fine-Tuning and LoRA and Parameter-Efficient Fine-Tuning chapters explain what fine-tuning is: continuing to train a pretrained model on your own examples, usually by learning a small set of extra weights instead of changing all of them. This chapter is the practical recipe. By the end you'll know how to take a small open model, teach it a narrow task from a few hundred to a few thousand examples on a single consumer GPU, check that it really improved, and package it for serving.
Fine-tuning a small model can be very worthwhile. A 1.5-billion-parameter model tuned for one job, say turning support emails into structured tickets, can match a far larger general model on that job. It then runs faster, costs much less per request, and can run on your own hardware where data must not leave the building (Running Models Locally).
But fine-tuning is also the most over-used technique in applied AI. So we start with when not to do it.
When not to fine-tune
Work up this ladder, and stop at the first rung that meets your quality bar on your eval set:
- Better prompting (Prompt Engineering): clear instructions, a few examples, and an output schema (Structured Output and JSON). This costs an afternoon.
- Retrieval (Retrieval-Augmented Generation): if the model lacks knowledge (your products, your policies, this week's prices), give it the documents at question time. Fine-tuning is a poor way to add facts. It teaches them unreliably, and the facts go stale.
- A bigger or better model, which is often cheaper than your engineering time.
- Fine-tuning, when you need one of the things it is good at:
- a consistent format or style that prompting can't hold reliably,
- a narrow, repetitive task done by a smaller, cheaper, faster model,
- behaviour that is hard to describe in words but easy to show by example,
- shorter prompts, because examples baked into the weights no longer have to be sent with every request.
Key idea Fine-tuning changes how a model behaves (format, style, a narrow skill), not what it knows. Build the eval set first, try prompting and RAG first, and fine-tune only when you can measure that it beats them.
The intuition
Think of the base model as an experienced professional joining your company. They already know the language, the general craft and a lot of the world. You don't send them back to university (pretraining), and you don't rewrite their personality (full fine-tuning). You give them a binder of a few hundred worked examples of how your team does things. That is fine-tuning.
LoRA makes the binder small. The model's billions of original weights are frozen. Next to some of its weight matrices you train a pair of thin matrices whose product is a low-rank correction. These are the LoRA adapter: often tens of megabytes beside a model of several gigabytes. QLoRA (Dettmers et al., 2023) adds one more trick. It stores the frozen original weights in 4 bits instead of 16, which cuts their memory by about four times. Gradients still flow through the 4-bit weights into the 16-bit adapters, so training quality stays close to normal LoRA. The QLoRA paper fine-tuned a 65-billion-parameter model on a single 48 GB GPU.
How it works
The whole job has seven steps.
Step 1: write the eval set and measure a baseline
Before any training, take 50 to 200 representative inputs with correct outputs and put them aside as the test set. Never train on them. Run the base model (with your best prompt) and, if relevant, a large API model on it, and record their scores. These are the numbers your fine-tune must beat. Evaluating LLM Applications shows how to build the harness.
Step 2: prepare the data
Each training example is one conversation: the input as the model will see it in production, and the ideal answer. The format TRL handles most cleanly is a prompt-completion dataset in chat form, one JSON object per line of a .jsonl file:
{"prompt": [{"role": "system", "content": "Extract a support ticket as JSON."},
{"role": "user", "content": "Order 1043 arrived with a cracked screen. I want a refund."}],
"completion": [{"role": "assistant", "content": "{\"order\": 1043, \"issue\": \"damaged\", \"wants\": \"refund\"}"}]}
Three details matter:
- The chat template. Every chat model was trained with a particular way of wrapping messages in special tokens, such as
<|im_start|>user ... <|im_end|>for Qwen. That wrapping is its chat template, stored with the tokenizer. TRL applies it for you. You must use the same template, with the same system prompt, when you serve the model. A mismatch quietly ruins the results. - Loss on the completion only. You want the model to learn to write answers, not to predict users' questions. With a prompt-completion dataset, TRL masks the prompt tokens out of the loss (sets their labels to −100) by default, the loss masking idea.
- Quality over quantity. A few hundred to a few thousand clean, consistent, diverse examples beat tens of thousands of noisy ones. The LIMA paper (2023) got a strong general chat model from just 1,000 carefully chosen examples. Remove duplicates, fix wrong labels, and cover the hard cases in proportion to how often they occur.
Split the remaining data into training and validation sets (say 90/10). The validation set tells you during training when to stop.
Step 3: choose a base model
Choose a small instruction-tuned model (the "-Instruct" or "-it" variants) whose licence allows your use, and that is big enough for the task. For extraction and classification, 0.5 to 4 billion parameters is often plenty. For open-ended writing, consider 7 to 14 billion. Examples include the Qwen, Llama, Gemma and Mistral families, available on the Hugging Face Hub. Our example uses Qwen/Qwen2.5-1.5B-Instruct (Apache 2.0 licence, 1.54 billion parameters).
Step 4: configure QLoRA
Three configuration objects describe the job:
- Quantization (
BitsAndBytesConfig): load the frozen weights in 4 bits with the NF4 ("4-bit NormalFloat") data type introduced by QLoRA, which suits normally distributed weights. Add double quantization (compressing the scaling constants too) and do the arithmetic in bf16. See Quantization. - LoRA (
LoraConfig):- The LoRA rank is the width of the thin matrices. Common values are 8 to 64, and 16 is a good default.
lora_alphais a scaling factor. The adapter's output is multiplied by , so is a common choice.target_modules="all-linear"puts adapters on every linear layer (attention and MLP). This usually works better than attention only.lora_dropoutof 0.05 adds light regularisation.
- Training (
SFTConfig): the usual training-loop settings.
| Setting | Typical value | Why |
|---|---|---|
| learning rate | 1e-4 to 2e-4 | LoRA tolerates about 10× the rate used for full fine-tuning |
| epochs | 1 to 3 | more tends to overfit small datasets |
| batch size × gradient accumulation | 4 × 4 = 16 | gradient accumulation sums gradients over several small batches before each update, giving a bigger effective batch without more memory |
| max length | longest real example, e.g. 1,024 tokens | longer sequences cost memory, and truncated examples teach the wrong thing |
| scheduler, warmup | cosine, ~3% warmup | a gentle start and a smooth decay (Learning Rate Schedules) |
| gradient checkpointing | on | gradient checkpointing recomputes activations during the backward pass instead of storing them: about 20% slower, much less memory |
| optimizer | paged_adamw_8bit |
QLoRA's paged 8-bit Adam avoids out-of-memory spikes |
A worked example of the step arithmetic: 1,000 training examples with an effective batch of 16 make optimizer steps per epoch. Three epochs make 189 steps, and 3% warmup is about 6 steps. With Qwen2.5-1.5B, rank 16 on all linear layers adds 18.5 million trainable parameters, 1.2% of the model. The arithmetic: each of its 28 layers has seven linear layers, and an adapter on a matrix has parameters. That gives 659,456 per layer.
Step 5: train and watch the curves
During training TRL logs the training loss, the validation loss and the token accuracy. The healthy pattern is both losses falling and the validation loss levelling off. If the validation loss turns up while the training loss keeps falling, the model is memorising (Overfitting and the Bias–Variance Tradeoff): use fewer epochs, more data or a lower learning rate. A loss that hardly moves suggests the learning rate is too low or the data is badly formatted. Print one tokenized example and check where the masking starts.
Step 6: evaluate against the baseline
Run the same eval harness on the tuned model and compare it with Step 1. Look at per-tag results, not only the average. Then check what you might have broken. Ask the tuned model a few ordinary questions outside the task. Heavy fine-tuning on a narrow format can make a model worse at everything else (a mild form of catastrophic forgetting). That's often acceptable for a single-purpose model, but you should know about it.
Step 7: merge the adapter and export
The trained adapter is a small separate file. To serve it you can either load base model plus adapter at run time (some servers, such as vLLM, can serve many adapters on one base model), or merge it: add the low-rank update into the base weights to get an ordinary model with no extra layers and no extra latency. Merge into a 16-bit copy of the base model, not the 4-bit one, so you don't bake quantization error into the result. The merged model can then be quantized again for serving, for example converted to GGUF for llama.cpp or Ollama (Running Models Locally).
In code
The full QLoRA script. It needs an NVIDIA GPU with CUDA (a free Colab T4 or any 12 GB+ card is enough for a 1.5B model), so it can't run here. It is written against transformers 5.24, peft 0.22, trl 1.19 and bitsandbytes 0.50 (current as of late 2026). The same pipeline without the 4-bit loading was run end to end on CPU with a tiny test model to check the API calls. Install with pip install transformers peft trl bitsandbytes datasets accelerate.
# train.py: QLoRA fine-tune of a small instruct model on prompt-completion JSONL
import torch
from datasets import load_dataset
from peft import LoraConfig
from transformers import BitsAndBytesConfig
from trl import SFTConfig, SFTTrainer
MODEL = "Qwen/Qwen2.5-1.5B-Instruct"
bf16 = torch.cuda.is_bf16_supported() # False on older GPUs such as the T4
dtype = torch.bfloat16 if bf16 else torch.float16
data = load_dataset("json", data_files="tickets_train.jsonl", split="train")
data = data.train_test_split(test_size=0.1, seed=42) # train / validation
quant = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4",
bnb_4bit_use_double_quant=True, bnb_4bit_compute_dtype=dtype)
lora = LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05,
target_modules="all-linear", task_type="CAUSAL_LM")
args = SFTConfig(
output_dir="qwen-tickets-qlora",
num_train_epochs=3,
per_device_train_batch_size=4, gradient_accumulation_steps=4, # effective batch 16
learning_rate=2e-4, lr_scheduler_type="cosine", warmup_steps=0.03, # float = ratio
max_length=1024,
gradient_checkpointing=True, optim="paged_adamw_8bit",
bf16=bf16, fp16=not bf16,
eval_strategy="epoch", save_strategy="epoch", logging_steps=10,
model_init_kwargs={"dtype": dtype},
report_to="none",
)
trainer = SFTTrainer(model=MODEL, args=args, quantization_config=quant, peft_config=lora,
train_dataset=data["train"], eval_dataset=data["test"])
trainer.model.print_trainable_parameters()
# trainable params: ~18.5M || all params: ~1.56B || trainable%: ~1.2
trainer.train()
trainer.save_model("qwen-tickets-adapter") # saves only the adapter (tens of MB)
Then merge the adapter into a 16-bit copy of the base model and try it:
# merge.py: fold the adapter into the base weights for simple serving
import torch
from peft import PeftModel
from transformers import AutoModelForCausalLM, AutoTokenizer
base = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-1.5B-Instruct", dtype=torch.bfloat16)
model = PeftModel.from_pretrained(base, "qwen-tickets-adapter").merge_and_unload()
tok = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-1.5B-Instruct")
model.save_pretrained("qwen-tickets-merged"); tok.save_pretrained("qwen-tickets-merged")
msgs = [{"role": "system", "content": "Extract a support ticket as JSON."},
{"role": "user", "content": "Parcel 2210 never came. Send a replacement please."}]
inputs = tok.apply_chat_template(msgs, add_generation_prompt=True, return_tensors="pt", return_dict=True)
out = model.generate(**inputs, max_new_tokens=60, do_sample=False)
print(tok.decode(out[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True))
# expected after a successful fine-tune, e.g.:
# {"order": 2210, "issue": "not delivered", "wants": "replacement"}
Finally, run your eval harness on qwen-tickets-merged and on the base model and compare. If the tuned model doesn't clearly win on held-out cases, don't ship it.
Libraries such as Unsloth wrap the same recipe with hand-written GPU kernels, which makes it faster and lighter on memory. Hosted services, including OpenAI's fine-tuning API and several cloud platforms, run the training for you from a JSONL file. The data preparation and evaluation steps stay exactly the same.
Common pitfalls
- Fine-tuning to add knowledge. The model will half-learn your facts and then state them confidently, out of date and sometimes wrong. Use Retrieval-Augmented Generation for knowledge.
- No baseline. Without Step 1 you can't tell whether three hours of training beat a better prompt.
- Template mismatch. Training with one chat template or system prompt and serving with another is the most common reason a tuned model "doesn't work". Serve with exactly the formatting you trained with.
- Training on the prompt. Forgetting to mask prompts wastes capacity and can make the model echo inputs. Check one tokenized example: prompt labels should be −100.
- Test-set leakage. Near-duplicates of test cases in the training data inflate scores. Deduplicate across splits.
- Too many epochs. On small datasets, watch the validation loss and stop early. One to three epochs is usually right.
- Merging into 4-bit weights. Merge into a 16-bit base, then quantize the merged model if you need to.
- bf16 on old GPUs. Pre-Ampere cards (such as the T4) lack fast bf16. Use fp16 there, as the script does.
Watch out Fine-tuning can remove a model's safety behaviour, even with harmless-looking data. Studies have found that a small number of fine-tuning examples can undo refusal training. If your tuned model faces the public, re-run safety and misuse tests on it, not just your task eval.
Where it leads
- Running Models Locally: convert the merged model to GGUF and run it with llama.cpp or Ollama.
- Serving LLMs at Scale: serve the base model with several LoRA adapters at once, one per customer or task.
- Knowledge Distillation and Small Models: generate training data with a large model and fine-tune a small one on it, a common way to build the dataset for this chapter.
- RLHF and Preference Optimization and preference tuning (DPO, available in TRL as
DPOTrainer): the next step after supervised fine-tuning, when you have "better versus worse" pairs instead of single correct answers. - Building AI Products: decide whether a tuned small model or an API model is the better product choice once cost and maintenance are counted.
A bit of history
Fine-tuning whole pretrained networks became standard with Transfer Learning in vision and with ULMFiT and BERT in 2018. As models grew to billions of parameters, full fine-tuning became too expensive for most people. Adapters (Houlsby et al., 2019) and LoRA (Hu et al., Microsoft, 2021) showed that training a tiny fraction of new parameters works almost as well. QLoRA (Dettmers et al., University of Washington, May 2023) combined LoRA with 4-bit NF4 quantization, double quantization and paged optimizers, and released Guanaco, a chat model tuned on a single GPU. Together with Hugging Face's PEFT and TRL libraries and open models such as Llama, Mistral and Qwen, this put fine-tuning within reach of anyone with a gaming GPU or a free notebook. Tools like Axolotl and Unsloth then turned the recipe into a configuration file.
Try it
- Compute the number of trainable LoRA parameters for rank 8 and rank 64 on Qwen2.5-1.5B (28 layers, hidden size 1536, MLP size 8960, key/value width 256). How does the count scale with ?
- Write a 30-example
tickets_train.jsonlby hand or with a model, keeping 10 more as a test set. Run the eval harness from Evaluating LLM Applications on the base model with a prompt. Can prompting alone reach 90%?- With a GPU: run
train.pyfor 1 and then 3 epochs. Compare validation loss and test-set accuracy. Did the third epoch help?Hint for 1: the count is linear in . Rank 16 gives 18.46 million, so rank 8 gives about 9.2 million and rank 64 about 73.9 million.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
TRL documentation
Transformer Reinforcement Learning: trainers for supervised fine-tuning (SFT), reward modelling, PPO, DPO and GRPO on Hugging Face models.
PEFT documentation
The standard library for LoRA, QLoRA, prefix tuning, prompt tuning and other parameter-efficient methods, with conceptual guides and runnable examples.
QLoRA: Efficient Finetuning of Quantized LLMs
LoRA on top of a 4-bit quantized frozen model, with the NF4 data type and paged optimizers. Made fine-tuning a 65B model possible on a single 48 GB GPU.
Hugging Face LLM Course
Using Transformers, datasets and tokenizers, fine-tuning, and building with open LLMs, with runnable notebooks.
How to fine-tune open LLMs in 2025 with Hugging Face
An end-to-end walk-through with TRL and PEFT: dataset preparation, QLoRA training, evaluation and deployment, with notes on newer techniques. Check library versions as APIs move.
Unsloth
An open-source library that makes LoRA and QLoRA fine-tuning of popular open models faster and lighter on memory, with free Colab notebooks for many models.
LIMA: Less Is More for Alignment
Fine-tunes a 65B base model on just 1,000 carefully chosen examples and gets a strong assistant, evidence that most knowledge comes from pretraining.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/building/fine-tuning-in-practice.md