Sub topic 11
Evaluating against the base model
This chapter assumes you can run a Hugging Face transformers model for inference, have trained a LoRA adapter with PEFT and TRL as in the previous chapters, and know basic Python and PyTorch. Training loss going down shows that the adapter fits the training data. It does not show that the model is better at the job you care about. This chapter shows how to measure that by comparing the fine-tuned model with the base model on data neither has trained on.
Why training loss is not enough
Training loss measures how well the model predicts the training tokens. A low value can come from real learning or from memorization. A fine-tuned model can also get better at your task while getting worse at other things. You need three checks:
- Held-out loss and perplexity. How well does the model predict text it has never trained on?
- Task metrics. Does the model produce correct, well-formatted answers?
- Regression checks. Did the adapter damage general abilities the base model had?
Every check should compare the adapter against the base model under identical conditions. A number such as "accuracy 72%" means little until you know the base model scores 65% or 40% on the same prompts.
Build a clean held-out split
Split your data before training and never touch the evaluation portion during training or hyperparameter tuning.
from datasets import Dataset
records = [
{"prompt": f"Summarize: item {i}", "reference": f"Summary {i}"}
for i in range(100)
]
ds = Dataset.from_list(records).shuffle(seed=42)
split = ds.train_test_split(test_size=0.2, seed=42)
train_ds, eval_ds = split["train"], split["test"]
print(len(train_ds), len(eval_ds))Common errors at this step:
- Leakage through near-duplicates. If the same support ticket appears twice with small edits, one copy can land in each split. Deduplicate before splitting.
- Split by the wrong unit. If one customer or document produces many examples, split by customer or document, not by row.
- Tuning on the test set. If you pick the learning rate or rank by looking at the evaluation set, it is no longer held out. Keep a separate validation set for choices and a final test set for the report.
Held-out loss and perplexity
Perplexity is the exponential of the average per-token cross-entropy loss. Lower is better. It is cheap to compute and works on any text, so it is a good first signal.
You can let the trainer compute it during training by passing eval_dataset and setting an evaluation schedule.
from peft import LoraConfig
from trl import SFTConfig, SFTTrainer
trainer = SFTTrainer(
model="Qwen/Qwen2.5-0.5B-Instruct",
train_dataset=train_chat,
eval_dataset=eval_chat,
args=SFTConfig(
output_dir="lora-out",
num_train_epochs=2,
per_device_train_batch_size=1,
learning_rate=2e-4,
eval_strategy="steps",
eval_steps=50,
logging_steps=10,
),
peft_config=LoraConfig(r=16, lora_alpha=32, task_type="CAUSAL_LM"),
)
trainer.train()Here train_chat and eval_chat are datasets in the messages format from the data preparation chapter. The trainer logs eval_loss at each evaluation step. Compute perplexity as math.exp(eval_loss).
Read the two curves together:
| Pattern | Meaning |
|---|---|
| Train and eval loss both fall | The adapter is learning something that generalizes. |
| Train loss falls, eval loss rises | Overfitting. Stop earlier, lower the rank or learning rate, or add data. |
| Both stay flat | Learning rate too low, wrong target modules, or data the model already handles well. |
| Eval loss lower, but outputs look worse | Loss and task quality disagree. Rely on task metrics. |
Perplexity has limits. It is only comparable between models that share a tokenizer, and it says nothing about whether generated answers are correct.
Compare base and adapter on the same data
PEFT lets you turn the adapter off temporarily with the disable_adapter() context manager. That gives you the base model's behavior from the same loaded weights, with no second copy in memory.
import math
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from peft import PeftModel
base_id = "Qwen/Qwen2.5-0.5B-Instruct"
tok = AutoTokenizer.from_pretrained(base_id)
base = AutoModelForCausalLM.from_pretrained(base_id)
model = PeftModel.from_pretrained(base, "lora-out/adapter")
model.eval()
texts = [
"Question: What does LoRA train?\nAnswer: Small low-rank matrices.",
"Question: What stays frozen?\nAnswer: The base model weights.",
]
@torch.no_grad()
def mean_loss(m, texts):
total, count = 0.0, 0
for t in texts:
enc = tok(t, return_tensors="pt")
out = m(**enc, labels=enc["input_ids"])
n = enc["input_ids"].shape[1] - 1
total += out.loss.item() * n
count += n
return total / count
adapter_loss = mean_loss(model, texts)
with model.disable_adapter():
base_loss = mean_loss(model, texts)
print("base perplexity: ", math.exp(base_loss))
print("adapter perplexity:", math.exp(adapter_loss))This weights each text by its token count, so long examples count proportionally. A real evaluation should use your full held-out set and, for chat data, should mask the prompt tokens so the loss covers only the assistant reply.
Task metrics on generated output
Generation-based evaluation is closer to real use. The procedure is the same for every task:
- Generate an answer for each held-out prompt with fixed settings.
- Score each answer against a reference or a rule.
- Repeat for the base model and the adapter.
- Compare the scores and report the difference.
Fix the generation settings. Use greedy decoding (do_sample=False) so differences come from the model and not from sampling randomness. Use the same chat template and the same max_new_tokens for both models.
import torch
@torch.no_grad()
def generate_answer(m, prompt, max_new_tokens=64):
messages = [{"role": "user", "content": prompt}]
ids = tok.apply_chat_template(
messages, add_generation_prompt=True, return_tensors="pt"
)
out = m.generate(ids, max_new_tokens=max_new_tokens, do_sample=False)
return tok.decode(out[0, ids.shape[1]:], skip_special_tokens=True).strip()
def exact_match(pred, ref):
return pred.strip().lower() == ref.strip().lower()
prompts = ["Summarize: LoRA trains small low-rank matrices."]
refs = ["LoRA adapts a model by training only small low-rank matrices."]
def score(m):
hits = [exact_match(generate_answer(m, p), r) for p, r in zip(prompts, refs)]
return sum(hits) / len(hits)
adapter_score = score(model)
with model.disable_adapter():
base_score = score(model)
print(f"base: {base_score:.2f} adapter: {adapter_score:.2f}")Choose the metric to fit the task:
| Task | Suitable metric |
|---|---|
| Classification or extraction | Accuracy, F1, exact match |
| Structured output such as JSON | Fraction of outputs that parse and match the schema |
| Summarization or free text | ROUGE as a rough signal, plus human or model-based grading |
| Code | Unit tests passed |
| Style or tone | Human ratings or a rubric-based judge |
Exact match is harsh for free text, where a correct answer can use different words. Use it only when the answer space is narrow.
Using a model as a judge
For open-ended answers, a stronger model can grade outputs against a rubric. This scales well but has known biases: judges tend to prefer longer answers and the first answer shown. Randomize the order of the base and adapter answers, keep the rubric fixed, and spot-check a sample of judgments by hand.
Check for forgetting
Fine-tuning on a narrow dataset can erode skills outside it. This is catastrophic forgetting. Test it by running a small set of general prompts, unrelated to your task, through both models. Examples are simple arithmetic, a general knowledge question, and an instruction that does not match your task format. Compare the answers, or compute perplexity on general text. A large rise in perplexity on general text or visibly worse answers means the adapter is too aggressive.
Common errors in evaluation
- Different prompts for each model. If the base model sees a plain prompt and the adapter sees the chat template, you are measuring the template, not the adapter. Use one formatting function.
- Forgetting
model.eval(). LoRA dropout stays active in training mode and adds noise to your metrics. - Sampling noise. With sampling on, a single run can differ by several points. Use greedy decoding, or average over several seeds and report the spread.
- Tiny evaluation sets. With 20 examples, one answer changes the score by 5 points. Use enough examples that a difference you care about is larger than the noise, and report counts alongside percentages.
- Comparing against the wrong baseline. Also try a strong prompt on the base model, such as a clear instruction plus a few examples. If the prompted base model matches the adapter, fine-tuning may not be worth its cost.
- Merged versus unmerged results. Merging can change outputs slightly through rounding, especially on a quantized base. Evaluate the model you will deploy.
Decide what to do with the result
Use the comparison to make a decision:
- If the adapter beats the base on the task metric and shows no regression on general prompts, keep it.
- If it beats the base but regresses on general prompts, lower the rank or learning rate, train for fewer epochs, or mix general instruction data into training.
- If it is no better than the base, check the chat template, the data quality, and the target modules before adding capacity.
- If it beats the base only on training-like examples, you have overfit. Add more varied data.
Exercise
Your training loss falls steadily, but eval loss reaches its minimum at step 200 and then rises until step 600. The adapter generates fluent answers on training prompts and weaker ones on new prompts. What is happening, and what are two changes you could try? Also name one setup mistake that would make a base-versus-adapter comparison invalid.
Show answer
The adapter is overfitting: after step 200 it memorizes the training examples instead of learning patterns that generalize. Two options are to stop training near step 200 (early stopping or load the best checkpoint) and to reduce capacity or exposure, for example by lowering the rank, lowering the learning rate, using fewer epochs, or adding more varied data. A comparison is invalid if the two models get different prompt formatting, different generation settings, or if the evaluation data was used during training or tuning.
Exercise
Write the one-line context manager call that lets you score the base model using a loaded PeftModel named model, and explain why you would call model.eval() before scoring.
Show answer
Use with model.disable_adapter(): and run the scoring code inside the block. Call model.eval() first because it turns off LoRA dropout, so the outputs are deterministic under greedy decoding and the metrics are not perturbed by dropout noise.