New cohort: Agentic AI & LLM Engineering remote internship. Limited seats.Apply now
Lesson 18 of 21 24 minFree

Fine-Tuning LLMs

When fine-tuning beats prompting and RAG, how training works, how to prepare data, and efficient methods like LoRA and QLoRA, with a 3D loss landscape.

By the end of this lesson you will be able to:

  • Decide when fine-tuning is the right tool, and when it isn't.
  • Explain how training reduces "loss" with gradient descent and a learning rate.
  • Prepare a clean training dataset in the chat JSONL format.
  • Describe efficient fine-tuning (LoRA and QLoRA) and how to evaluate the result.

What is fine-tuning?

A foundation model has learned general language from enormous amounts of text. Fine-tuning continues its training on a much smaller set of your examples, so it picks up a specific behaviour: a format, a tone, a narrow skill or domain vocabulary. The model's weights actually change, unlike prompting or RAG.

Our study buddy has a problem prompts can't fully fix. Teachers want worksheet feedback in a very specific style: one encouraging line, three numbered corrections, and a "next practice" suggestion, every single time, in simple Indian English. After 500 examples written by good teachers, a fine-tuned model does it reliably with a much shorter prompt.

Should you fine-tune? Usually, not first

Remember the improvement ladder from Lesson 2: prompt engineering → RAG → fine-tuning → training from scratch.

Don't fine-tune when…

Good prompts with a few examples already work. The problem is missing knowledge or changing facts (use RAG). You have fewer than ~50–100 high-quality examples. Or you can't evaluate the result.

Fine-tune when…

You need a consistent style or format at scale. You want a smaller, cheaper model to match a bigger one on one narrow task. Prompts are getting very long. Or you have hundreds of good examples and an evaluation set.

How training works: rolling downhill

Training measures how wrong the model is on your examples. This is the loss. It then nudges millions of weights in the direction that reduces it, a little at a time, using gradient descent. Imagine a ball rolling down a hilly landscape towards the lowest valley. The learning rate is how big each step is. Try all three below:

  • Epoch: one pass through all your training examples.
  • Overfitting: the model memorises your examples and gets worse on new inputs. Watch the loss on a held-out validation set, and stop when it starts rising.
  • Catastrophic forgetting: training too hard on a narrow task can damage general skills. Use few epochs and a small learning rate.

Preparing the data

Data quality matters more than anything else. Most chat-model fine-tuning uses JSONL: one JSON object per line, each holding a full example conversation.

{"messages": [{"role": "system", "content": "You give worksheet feedback to Class 6 students."}, {"role": "user", "content": "Q: 3/4 + 1/4 = ? Student answer: 4/8"}, {"role": "assistant", "content": "Great try! 🌟\n1. When the denominators are the same, add only the numerators: 3 + 1 = 4.\n2. Keep the denominator: 4/4.\n3. 4/4 simplifies to 1.\nNext practice: 2/5 + 1/5."}]}
  • Consistent: every example shows exactly the behaviour you want.
  • Diverse: cover different subjects, mistakes and difficulty levels.
  • Clean and safe: no personal data, no errors, reviewed by experts.
  • Split: keep 10–20% aside for validation and evaluation.

Efficient fine-tuning: LoRA and QLoRA

Updating every weight of a large model needs huge GPUs. Parameter-efficient fine-tuning (PEFT) trains only a tiny add-on instead:

  • LoRA (Low-Rank Adaptation): freezes the original weights and learns small "adapter" matrices, often well under 1% of the parameters. Adapters are small files you can swap per task.
  • QLoRA: LoRA on a model loaded in 4-bit precision, so a 7–8B model can be fine-tuned on a single consumer GPU.

Tools: Hugging Face transformers, peft and trl (for example its SFTTrainer) for open models. Or managed fine-tuning in Azure AI Foundry or OpenAI's API: upload your JSONL, start a job, get a custom model ID.

Hands-on

Your task: turn the teacher-reviewed pairs into chat-format JSONL lines. Then complete is_valid(): a line is valid if it parses as JSON, has a messages list, and the last message has role "assistant" with non-empty content. Expected: Valid examples: 2 of 3, because one pair has an empty answer.

import json

SYSTEM = "You give short, encouraging worksheet feedback to Class 6 students."
pairs = [
    ("Q: 7 x 8 = ? Student: 54", "Nice effort! 🌟\n1. 7 x 8 = 56.\nNext practice: 7 x 9."),
    ("Q: Capital of Kerala? Student: Kochi", "Good thinking!\n1. The capital is Thiruvananthapuram; Kochi is a big port city.\nNext practice: capital of Karnataka."),
    ("Q: 3/4 + 1/4 = ? Student: 4/8", ""),
]

lines = []
for question, answer in pairs:
    example = {"messages": [
        {"role": "system", "content": SYSTEM},
        {"role": "user", "content": question},
        {"role": "assistant", "content": answer},
    ]}
    lines.append(json.dumps(example, ensure_ascii=False))

def is_valid(line):
    # TODO: parse with json.loads (return False on error), check "messages" is a list,
    #       and the last message has role "assistant" and non-empty content
    return True

valid = [l for l in lines if is_valid(l)]
print(lines[0][:90] + "...")
print(f"Valid examples: {len(valid)} of {len(lines)}")
Show solution
def is_valid(line):
    try:
        data = json.loads(line)
    except json.JSONDecodeError:
        return False
    msgs = data.get("messages")
    if not isinstance(msgs, list) or not msgs:
        return False
    last = msgs[-1]
    return last.get("role") == "assistant" and bool(last.get("content", "").strip())

Your task: this tiny "model" has one weight w, and its loss is (w - 3)², so the best value is 3. The gradient is 2 × (w - 3). Write the update step w = w - learning_rate × gradient. Then try learning rates 0.01 and 1.1 to see "too slow" and "exploding". Expected with 0.1: Converged: w = 3.00.

learning_rate = 0.1
w = 0.0

def loss(w):
    return (w - 3) ** 2

for epoch in range(1, 61):
    gradient = 2 * (w - 3)
    # TODO: update w using the learning rate and gradient
    if epoch in (1, 5, 10, 20, 40, 60):
        print(f"epoch {epoch:2}: w = {w:8.4f}   loss = {loss(w):10.4f}")

print(f"Converged: w = {w:.2f}" if abs(w - 3) < 0.01 else f"Not converged: w = {w:.2f}")
Show solution
    w = w - learning_rate * gradient

Check your understanding

Answers must follow the school's newest fee rules, which change every term. Fine-tuning or RAG?

  1. Fine-tuning, retrained every term
  2. RAG, because it's changing knowledge
  3. Neither
  4. Train a model from scratch

Fine-tuning is for behaviour and style. Changing facts belong in RAG.

Training loss keeps falling, but validation loss starts rising. What's happening?

  1. The learning rate is perfect
  2. The model needs more epochs
  3. The data is too diverse
  4. Overfitting: it's memorising the training examples

Stop training when validation loss starts to rise.

Why is LoRA popular?

  1. It trains small adapter weights instead of the whole model, so it's much cheaper
  2. It removes the need for training data
  3. It makes models bigger
  4. It only works with proprietary models

LoRA freezes the base model and learns small adapters, which cuts memory and cost dramatically.

Key takeaways

  • Fine-tune for consistent behaviour, style or narrow skills, after prompts and RAG.
  • Training minimises loss with gradient descent. The learning rate and epochs matter, so watch for overfitting.
  • Clean, consistent, reviewed JSONL data is the biggest success factor.
  • LoRA and QLoRA make fine-tuning affordable. Always compare against your baseline.

Next: small language models that run on laptops and phones.

Your progress is saved in this browser.

Adapted from Lesson 18 of Microsoft's "Generative AI for Beginners" (MIT License), rewritten and extended by Aiprojects4U. View source