Do you actually need to fine-tune?
Fine-tuning changes the weights. It is powerful, but it is not always the right tool. Try the cheaper options first.
| What changes | Good for | Not good for | |
|---|---|---|---|
| Prompting | Only the text you send | Most tasks; quick tests; changing instructions often | Very long instructions repeated on every call |
| Retrieval (RAG) | The documents you add to the prompt | Facts that change; your own documents; citing sources | Teaching a style or a skill |
| Fine-tuning (LoRA) | A small add-on to the weights | A fixed format, style or narrow task; a smaller, cheaper model doing one job well | Adding lots of new facts; anything that changes weekly |
| Continued pretraining | All the weights, on lots of raw text | A new language or a whole new field | Small budgets |
Which tool fits each job best?
-
Answer questions about this week’s price list
Answer: Prompting or retrieval
-
Always reply in our exact JSON format, millions of times a day, with a small model
Answer: Fine-tuning
-
Summarise one long report
Answer: Prompting or retrieval
-
Write customer replies in our company’s voice
Answer: Fine-tuning
-
Look up a policy in a 500-page handbook
Answer: Prompting or retrieval
-
Turn doctors’ dictated notes into a fixed form, using a model small enough for a laptop
Answer: Fine-tuning
Full fine-tuning is expensive
Updating every weight means storing gradients and optimizer states for every weight too. The backprop lesson counted about 16 bytes per parameter with AdamW in mixed precision.
Rough figures. LoRA still stores the frozen model (16 GB at 16 bits, about 5 GB at 4 bits) but trains only a tiny add-on. Activations add more, depending on the length of the training texts.
LoRA: a small add-on to each matrix
LoRA (low-rank adaptation, Microsoft, 2021) freezes the original weights and adds a small correction to each chosen matrix. The correction is the product of two thin matrices, which together have very few numbers.
W′ = W + (α ÷ r) × B × AW is the frozen original. A has r rows, B has r columns; only A and B are trained. r is the rank, α a scaling number.
W: 4,096 × 4,096 = 16,777,216 numbersOne attention matrix in Llama 3.1 8B.
r = 16: A is 16 × 4,096 and B is 4,096 × 16 → 131,072 numbers0.78 % of the original matrix.
All 7 matrices of all 32 layers at r = 16 ≈ 42 million numbersAbout 0.5 % of the 8.03 billion weights.
Quick check
Microsoft found that, on GPT-3 175B, LoRA cut the trainable parameters by 10,000 times and the GPU memory by 3 times, with quality as good as full fine-tuning. After training, B × A can be added into W once, so the finished model runs exactly as fast as the original. Or the adapter can stay separate: servers such as vLLM and llama.cpp can load several adapters on one base model.
What the research says about settings
- Put LoRA on every layer, not just attention. Thinking Machines (2025) found LoRA works best on all weight matrices, especially the feed-forward and MoE layers; attention-only LoRA did worse even with as many parameters.
- Use a higher learning rate than full fine-tuning. The same study found the best learning rate for LoRA about 10 times higher than for full fine-tuning.
- For small and medium datasets, LoRA matches full fine-tuning. It falls behind only when the dataset is too big for the adapter’s capacity, such as continued pretraining on billions of tokens.
- For reinforcement learning, even very small ranks work. RL gives few bits of information per example, so a small adapter can hold what it learns.
- LoRA forgets less. A 2024 study found LoRA learns less than full fine-tuning on a new domain, but keeps more of the model’s other skills.
Your data
Most tools take a JSONL file: one JSON object per line, each one a whole conversation in the same messages format used by chat APIs.
{"messages": [{"role": "system", "content": "Turn the note into the clinic form."}, {"role": "user", "content": "pt 54M cough 3 wks no fever"}, {"role": "assistant", "content": "Age: 54\nSex: male\nComplaint: cough\nDuration: 3 weeks\nFever: no"}]}
{"messages": [{"role": "system", "content": "Turn the note into the clinic form."}, {"role": "user", "content": "f 31 headache since mon, fever 38.4"}, {"role": "assistant", "content": "Age: 31\nSex: female\nComplaint: headache\nDuration: since Monday\nFever: yes, 38.4 °C"}]}
- Every line is one complete example. Keep the system prompt the same as the one you will use later.
- The tool applies the model’s own chat template for you, so the model sees exactly the format it was post-trained on.
- Quality beats quantity: LIMA reached strong results with 1,000 careful examples. A few hundred consistent examples are often enough for a format or a style.
- Check every example by hand, or at least a large sample. The model will copy your mistakes faithfully.
- Cover the variety you expect: short and long inputs, typos, the awkward cases.
- Hold back 5 to 10 % as a validation set the model never trains on.
- Generating data with a bigger model? Check its licence and terms of use first: some forbid training other models on their outputs. Open models such as Qwen (Apache 2.0) and DeepSeek (MIT) allow it.
Run it
from datasets import load_dataset
from peft import LoraConfig
from trl import SFTConfig, SFTTrainer
data = load_dataset("json", data_files={"train": "train.jsonl", "test": "valid.jsonl"})
trainer = SFTTrainer(
model="Qwen/Qwen3-0.6B",
train_dataset=data["train"],
eval_dataset=data["test"],
args=SFTConfig(output_dir="clinic-form", num_train_epochs=2,
learning_rate=2e-4, assistant_only_loss=True),
peft_config=LoraConfig(r=16, lora_alpha=32, target_modules="all-linear"),
)
trainer.train()
modelcan be any model name on Hugging Face; TRL downloads it.assistant_only_loss=Truecounts the loss only on the assistant’s replies, as in the post-training lesson.target_modules="all-linear"puts LoRA on every linear layer, as the research above recommends.- The adapter is saved in
clinic-form/, a few megabytes instead of a whole model.
$ pip install mlx-lm
# a folder called data/ with train.jsonl and valid.jsonl
$ mlx_lm.lora --model Qwen/Qwen3-0.6B --train --data ./data --iters 600
# try it with the adapter
$ mlx_lm.generate --model Qwen/Qwen3-0.6B --adapter-path adapters \
--prompt "m 70, chest pain 2 days"
# merge the adapter into a standalone model
$ mlx_lm.fuse --model Qwen/Qwen3-0.6B
- The adapter is saved in
adapters/by default, and the merged model infused_model/. - Point
--modelat a 4-bit MLX model and it trains with QLoRA automatically.
Other popular tools: Unsloth, which makes LoRA faster and lighter on NVIDIA GPUs and has free notebooks; LLaMA-Factory, from a Chinese research team, with a no-code web interface for more than 100 models; and Axolotl, driven by one configuration file. TRL also has DPOTrainer and GRPOTrainer, so you can do the preference and RL steps of the last two lessons yourself.
Did it work?
Good signs
- Validation loss falls along with training loss
- Outputs on new examples have the right format and tone
- General skills, like simple maths or chatting, still work
Warning signs
- Training loss keeps falling while validation loss rises: overfitting, so stop earlier or add data
- The model repeats training examples word for word
- It forgot other skills: lower the learning rate, use fewer passes, or mix in general data
Always compare against the base model with a good prompt. If a careful prompt gets 95 % of the way, the fine-tune may not be worth maintaining. The evaluation lesson in Part 9 shows how to build a small test set that tells you for sure.
Remember
- Use prompting and retrieval for facts and changing instructions; fine-tune for fixed behaviour, format, style or a small specialist model.
- LoRA freezes W and trains a low-rank correction B × A: well under 1 % of the weights, and it can be merged back in.
- QLoRA trains the LoRA on a 4-bit frozen model, so big models fit on one GPU.
- Put LoRA on all layers, use a learning rate about 10 times higher than for full fine-tuning, and hold back a validation set.
- Data is a JSONL file of conversations; quality matters more than quantity.
- Tools: TRL and PEFT, mlx-lm on a Mac, Unsloth, LLaMA-Factory and Axolotl.
Words to know
- Fine-tuning
- Further training of an already trained model on your own examples.
- Full fine-tuning
- Updating every weight of the model. Powerful but memory-hungry.
- LoRA
- Low-rank adaptation: training a small add-on (B × A) for each matrix while the original stays frozen.
- Rank (r)
- The size of LoRA’s thin matrices. Higher rank means more capacity and more parameters.
- Adapter
- The small file of trained LoRA weights, loaded on top of a base model.
- QLoRA
- LoRA trained on top of a model stored in 4 bits, to save memory.
- PEFT
- Parameter-efficient fine-tuning: methods like LoRA that train only a few parameters; also the name of Hugging Face’s library.
- JSONL
- A file with one JSON object per line, the usual format for training examples.
- Overfitting
- Learning the training examples so closely that new inputs get worse answers.
- Catastrophic forgetting
- Losing earlier skills while learning a new task.
- Merging
- Adding the trained adapter into the original weights to make one standalone model.
Go to the source
This lesson is built on these papers and documents. Paper links open arxiv.org, a separate site.
-
LoRA: Low-Rank Adaptation of Large Language Models
Short and clear. Figure 1 is the whole idea in one picture.
-
QLoRA: Efficient Finetuning of Quantized LLMs
NF4, double quantization and paged optimizers, plus 1,000 fine-tuned models’ worth of lessons.
-
LoRA Without Regret (Thinking Machines)
Careful, modern experiments on when LoRA matches full fine-tuning, with practical settings.
-
LoRA Learns Less and Forgets Less
The trade-off between learning a new domain and keeping old skills.
-
LlamaFactory: Unified Efficient Fine-Tuning of 100+ Language Models
A tour of efficient fine-tuning methods, and the open framework built on them.
-
TRL documentation: SFT Trainer (Hugging Face)
The reference for the Python example in this lesson, kept up to date.
Check yourself
6 questions. Tap the answer you think is right.
0 of 6 answered
Lesson complete
Answer every question above to complete this lesson.
Your progress is saved on this device only.
Next lessonWhat happens when you press Enter