◆ AI All-in-One

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
↗ Plan a path here

Read first

LoRA and Parameter-Efficient Fine-TuningThe Hugging Face Ecosystem

This leads to

—
The full path from zero — 47 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Derivatives and Slopes
  4. Probability Basics
  5. Python for AI
  6. How Machines Learn
  7. Partial Derivatives and Gradients
  8. Matrices and Matrix Multiplication
  9. The Chain Rule
  10. Dot Product, Norms and Similarity
  11. Tokenization
  12. Supervised, Unsupervised and Reinforcement Learning
  13. Gradient Descent
  14. Tensors and Shapes
  15. Eigenvectors and SVD
  16. NumPy and Array Thinking
  17. Language Modeling and Next-Token Prediction
  18. Supervised Learning
  19. Linear Regression
  20. Training, Validation and Test Sets
  21. The Perceptron
  22. Logistic Regression
  23. Overfitting and the Bias–Variance Tradeoff
  24. Regularization: L1 and L2
  25. Neural Networks
  26. Recurrent Neural Networks
  27. Backpropagation
  28. Activation Functions
  29. Dropout and Regularizing Neural Networks
  30. PyTorch
  31. Vanishing and Exploding Gradients
  32. Normalization Layers: BatchNorm and LayerNorm
  33. Optimizers: SGD, Momentum and Adam
  34. LSTMs and GRUs
  35. Residual Connections
  36. Training Neural Networks in Practice
  37. Sequence-to-Sequence Models
  38. Transfer Learning
  39. Attention
  40. Self-Attention and Multi-Head Attention
  41. Positional Encodings
  42. The Transformer
  43. The Hugging Face Ecosystem
  44. GPT and Decoder-Only Models
  45. Pretraining Large Language Models
  46. Fine-Tuning
  47. LoRA and Parameter-Efficient Fine-Tuning
  48. 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:

  1. Better prompting (Prompt Engineering): clear instructions, a few examples, and an output schema (Structured Output and JSON). This costs an afternoon.
  2. 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.
  3. A bigger or better model, which is often cheaper than your engineering time.
  4. 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.

Full fine-tuning 16-bit weights + AdamW weights 16 GB gradients 16 GB fp32 copy 32 GB Adam states 64 GB ≈ 128 GB LoRA frozen 16-bit model weights 16 GB ≈ 16.7 GB16 GB frozen weights + 0.7 GB adapter with gradients and Adam state QLoRA frozen 4-bit model ≈ 6.4 GB5.7 GB frozen weights + 0.7 GB adapter with gradients and Adam state 0 16 24 48 80 128 GB of GPU memory (common GPU sizes: 16, 24, 48, 80 GB) 8-billion-parameter model; rank-16 adapters on all linear layers (≈42 million trainable parameters). Not shown: activations, a few GB depending on batch size and sequence length (gradient checkpointing shrinks them).
Fig. 1 GPU memory for fine-tuning an 8-billion-parameter model, before activations. Full fine-tuning with AdamW needs about 16 bytes per parameter (≈128 GB). LoRA freezes the 16-bit model and trains a tiny adapter (≈16.7 GB). QLoRA also stores the frozen model in 4 bits (≈6.4 GB; embeddings stay in 16-bit), so it fits on a single consumer GPU.

How it works

The whole job has seven steps.

1 Eval set score the base model and a prompt baseline 2 Prepare data chat-format JSONL, clean, deduplicated 3 Base model small, instruct, licence fits 4 Configure 4-bit NF4 + LoRA r=16 lr 2e-4, 1–3 epochs held-out test set never trained on 5 Train watch train and validation loss 6 Evaluate tuned vs baseline, per tag + side effects beats baseline? 7 Merge, export into 16-bit base; optionally GGUF yes no: fix data
Fig. 2 The fine-tuning workflow. The eval set exists before training starts; the same held-out test cases are used to compare the base model and the tuned model at the end.

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:

  1. 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.
  2. LoRA (LoraConfig):
    • The LoRA rank rr is the width of the thin matrices. Common values are 8 to 64, and 16 is a good default.
    • lora_alpha is a scaling factor. The adapter's output is multiplied by α/r\alpha / r, so α=2r\alpha = 2r 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_dropout of 0.05 adds light regularisation.
  3. 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 ⌈1000/16⌉=63\lceil 1000/16 \rceil = 63 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 din×doutd_{\text{in}} \times d_{\text{out}} matrix has r(din+dout)r(d_{\text{in}} + d_{\text{out}}) 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

  1. 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 rr?
  2. Write a 30-example tickets_train.jsonl by 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%?
  3. With a GPU: run train.py for 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 rr. Rank 16 gives 18.46 million, so rank 8 gives about 9.2 million and rank 64 about 73.9 million.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. Your chatbot doesn't know your company's current product prices. A colleague suggests fine-tuning. What does the chapter recommend instead?

  2. Your fine-tuned model worked in testing but gives garbled output in production. What is the most common cause?

  3. You have 1,000 training examples, a per-device batch of 4 and gradient accumulation of 4. How many optimizer steps per epoch?

  4. During training the training loss keeps falling but the validation loss starts rising. What should you do?

  5. You want to merge the trained LoRA adapter for simple serving. Into what should you merge it?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Docs

TRL documentation

Hugging Face · Intermediate · Free

Transformer Reinforcement Learning: trainers for supervised fine-tuning (SFT), reward modelling, PPO, DPO and GRPO on Hugging Face models.

Docs

PEFT documentation

Hugging Face · Intermediate · Free

The standard library for LoRA, QLoRA, prefix tuning, prompt tuning and other parameter-efficient methods, with conceptual guides and runnable examples.

Paper

QLoRA: Efficient Finetuning of Quantized LLMs

Dettmers et al. (University of Washington) · 2023 · Advanced · Free

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.

Course

Hugging Face LLM Course

Hugging Face · Intermediate · Free

Using Transformers, datasets and tokenizers, fine-tuning, and building with open LLMs, with runnable notebooks.

Tutorial

How to fine-tune open LLMs in 2025 with Hugging Face

Philipp Schmid · 2025 · Intermediate · Free

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.

Tool

Unsloth

Unsloth AI · Intermediate · Free

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.

Paper

LIMA: Less Is More for Alignment

Zhou et al. (Meta) · 2023 · Intermediate · Free

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