Availit World How AI really works, in your language

Lesson 22 of 4617 minFacts checked October 20, 2026

Fine-tuning: making a model your own

You do not need a data centre to change how a model behaves. With LoRA, you train well under 1 % of a model’s weights, on one GPU or a Mac, in an afternoon, and get a model that writes in your format, knows your style, or handles your task better than a model ten times its size. This lesson covers when fine-tuning is worth it, how LoRA works, and the commands to do it.

In this lesson you will

  • Decide between prompting, retrieval and fine-tuning for a real problem
  • Explain LoRA and QLoRA, and count a LoRA’s parameters
  • Prepare a training file and run a fine-tune with TRL or mlx-lm
  • Avoid the common mistakes: overfitting, forgetting and template mismatches
On this page
  1. Do you actually need to fine-tune?
  2. Full fine-tuning is expensive
  3. LoRA: a small add-on to each matrix
  4. What the research says about settings
  5. Your data
  6. Run it
  7. Did it work?
  8. Remember
  9. Check yourself

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.

Four ways to adapt a model
What changesGood forNot good for
PromptingOnly the text you sendMost tasks; quick tests; changing instructions oftenVery long instructions repeated on every call
Retrieval (RAG)The documents you add to the promptFacts that change; your own documents; citing sourcesTeaching a style or a skill
Fine-tuning (LoRA)A small add-on to the weightsA fixed format, style or narrow task; a smaller, cheaper model doing one job wellAdding lots of new facts; anything that changes weekly
Continued pretrainingAll the weights, on lots of raw textA new language or a whole new fieldSmall budgets

Which tool fits each job best?

0 of 6 sorted
  • 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.

Memory to fine-tune an 8B model, before activations
  • Full fine-tuning (about 16 bytes per weight) 128 GB
  • LoRA on a 16-bit model 17 GB
  • QLoRA on a 4-bit model 6 GB

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.

The LoRA formula
W′ = W + (α ÷ r) × B × A

W 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 numbers

One attention matrix in Llama 3.1 8B.

r = 16: A is 16 × 4,096 and B is 4,096 × 16 → 131,072 numbers

0.78 % of the original matrix.

All 7 matrices of all 32 layers at r = 16 ≈ 42 million numbers

About 0.5 % of the 8.03 billion weights.

Quick check

A matrix is 1,000 × 1,000. A LoRA of rank 8 is added. How many numbers does the LoRA train?

Show the answer

Answer: 16,000 A is 8 × 1,000 and B is 1,000 × 8: 8,000 + 8,000 = 16,000, which is 1.6 % of the million in the matrix.

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.

train.jsonl (two examples)json
{"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

LoRA with Hugging Face TRL (on an NVIDIA GPU)python
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()
  • model can be any model name on Hugging Face; TRL downloads it.
  • assistant_only_loss=True counts 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.
LoRA with mlx-lm (on a Mac)bash
$ 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 in fused_model/.
  • Point --model at 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.

Check yourself

6 questions. Tap the answer you think is right.

0 of 6 answered

You want a model to answer questions about documents that change every week. What is the best tool?

Show the answer

Answer: Retrieval: put the right passages in the prompt Retrieval gives the model exact, current text to read. Fine-tuning is weak at adding facts and slow to update.

What does LoRA train?

Show the answer

Answer: Two thin matrices per chosen weight matrix, while the original stays frozen W stays fixed; the trained correction is B × A, which has very few numbers.

Why can a merged LoRA model run as fast as the original?

Show the answer

Answer: Because B × A is added into W once, so there is no extra work per token After merging, the model has exactly the original shape; the adapter has become part of the weights.

What does QLoRA add to LoRA?

Show the answer

Answer: A 4-bit frozen base model, so much less memory is needed The frozen weights are stored in 4-bit NF4, and only the 16-bit adapter is trained.

Training loss keeps falling, but validation loss has started to rise. What is happening?

Show the answer

Answer: Overfitting: it is memorising the training examples It does better on what it has seen and worse on new examples. Stop earlier, or add more varied data.

Where does recent research say to put LoRA?

Show the answer

Answer: On all weight matrices, especially the feed-forward and MoE layers Attention-only LoRA did worse, even with the same number of parameters.

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
Previous lesson All lessons

Choose your language