Evaluate Before and After Training
A falling training loss does not prove your model got better. It only shows the model got better at your training examples. To know if fine-tuning helped, you test the model on held-out examples it never saw, and you compare the scores before and after training.
This lesson shows how to do that in the same Colab notebook from lesson 4.
What You'll Learn
- Why you need a "before" score from the base model
- How to generate answers on your test set
- Simple, honest metrics for your task
- How to spot overfitting with an evaluation loss
- How to read the results and decide what to fix
Why Before and After
Imagine your trained model gets 80% of test tickets right. Is that good? You cannot tell. If the base model with a good prompt already got 78%, training barely helped. If it got 20%, training made a big difference.
So you always measure twice, with the same test set and the same scoring code:
- Before: the base model, ideally with your best prompt.
- After: the fine-tuned model.
Step 1: Write a Generate Function
This function sends one test example to the model and returns its reply. It uses the system and user messages, and leaves out the correct assistant answer.
import torch
from unsloth import FastLanguageModel
def generate_reply(model, tokenizer, messages, max_new_tokens=128):
prompt_messages = messages[:-1] # system + user, no correct answer
inputs = tokenizer.apply_chat_template(
prompt_messages,
add_generation_prompt=True,
return_tensors="pt",
return_dict=False, # plain token tensor, not a dict
).to("cuda")
with torch.no_grad():
output = model.generate(input_ids=inputs, max_new_tokens=max_new_tokens,
do_sample=False)
new_tokens = output[0][inputs.shape[1]:]
return tokenizer.decode(new_tokens, skip_special_tokens=True).strip()
do_sample=False makes the model pick its most likely answer every time. Your scores then do not change from run to run by chance.
Before you call it, switch Unsloth into its faster inference mode:
FastLanguageModel.for_inference(model)
If you want to train again after testing, switch back with FastLanguageModel.for_training(model).
Step 2: Pick Simple Metrics
Choose metrics that match your task. For the support ticket project, three checks work well:
| Metric | What it checks |
|---|---|
| Valid JSON rate | Did the reply parse as JSON at all? |
| Category accuracy | Is the category field correct? |
| Urgency accuracy | Is the urgency field correct? |
These are cheap and objective. For open-ended tasks like writing in a certain tone, you can read a sample of replies yourself, or ask a large model to grade them against clear rules. Reading 20 replies yourself is always worth it.
Step 3: Score the Test Set
import json
def score(model, tokenizer, test_data):
valid = category_ok = urgency_ok = 0
for row in test_data:
reply = generate_reply(model, tokenizer, row["messages"])
expected = json.loads(row["messages"][-1]["content"])
try:
got = json.loads(reply)
except json.JSONDecodeError:
continue
valid += 1
category_ok += got.get("category") == expected["category"]
urgency_ok += got.get("urgency") == expected["urgency"]
n = len(test_data)
return {
"valid_json": round(valid / n, 2),
"category": round(category_ok / n, 2),
"urgency": round(urgency_ok / n, 2),
}
Run it twice:
- Before training: after you load the model and your test data in lesson 4, but before you add adapters with
get_peft_model. Save the result, for examplebefore = score(model, tokenizer, test_data). Then runFastLanguageModel.for_training(model)before you continue with lesson 4. - After training: once
trainer.train()finishes,after = score(model, tokenizer, test_data).
Then print both and compare. A typical result for a format task looks like this: the base model often writes friendly text around its JSON or uses its own field names, so its valid JSON rate is low. The fine-tuned model returns clean JSON nearly every time. Your own numbers will differ.
Step 4: Look at the Mistakes
The numbers tell you how often the model is wrong. The mistakes tell you why. Print the first 10 failures:
shown = 0
for row in test_data:
want = row["messages"][-1]["content"]
got = generate_reply(model, tokenizer, row["messages"])
if got == want:
continue
print("USER:", row["messages"][1]["content"])
print("WANT:", want)
print("GOT: ", got)
print("---")
shown += 1
if shown == 10:
break
Look for patterns. Does it always get one category wrong? Does it fail on long messages? A pattern usually points to a gap in your training data.
Spotting Overfitting
Overfitting means the model memorized your training examples instead of learning the pattern. It does great on training data and worse on new data.
To watch for it, give the trainer an evaluation set and ask it to report an evaluation loss during training. Keep your final test set separate. Split a small validation set off the training data:
parts = train_data.train_test_split(test_size=0.1, seed=42)
train_part, val_part = parts["train"], parts["test"]
Then pass eval_dataset=val_part to SFTTrainer, and add eval_strategy="steps" and eval_steps=20 to SFTConfig. Remember to apply the same to_text formatting to val_part.
Now read the two loss curves together:
| Training loss | Evaluation loss | What it means |
|---|---|---|
| Going down | Going down | Still learning. Fine |
| Going down | Flat | Learning is slowing. Stop soon |
| Going down | Going up | Overfitting. Stop earlier or use less training |
If you see overfitting, try one change at a time:
- Train for fewer epochs, often 1 is enough.
- Lower the learning rate.
- Use a smaller rank
r. - Add more varied training examples.
When the Results Are Bad
| Problem | Likely cause | Fix |
|---|---|---|
| No better than the base model | Too little or inconsistent data | Clean and grow the dataset |
| Good on test, bad on real messages | Test set too similar to training, or leakage | Rebuild the split, add real examples |
| Forgets general skills | Too much training on a narrow task | Fewer epochs, lower learning rate |
| Wrong output format | Chat template mismatch | Use the same template for training and testing |
Key Takeaways
- A low training loss is not proof. Test on held-out examples the model never saw.
- Always score the base model first, with the same test set and the same scoring code.
- Pick simple metrics for your task, and read a sample of real replies yourself.
- Watch training and evaluation loss together. If evaluation loss rises while training loss falls, the model is overfitting.
- Fix problems one change at a time, usually starting with your data.
Quiz
Up next · Lesson 6 of 6
Save, Share and Run Your Model
6 min read
5 of 6 lessons done

Ask Byte about this lesson
A private chat about this lesson. Byte has read the whole lesson, answers in seconds, and shows the section each answer comes from. Ask follow-ups in any language.
Questions & Answers
Public questions about this lesson. The AI Tutor answers right away in your language, the FreeAcademy team checks answers, and every learner can read them.

