Lab: Base vs Tuned on Held-Out Data
Evaluate the LoRA adapter from the previous lab properly: a strict JSON and schema check, per-field accuracy and exact match on test messages written in phrasings that training never saw, the base model zero-shot and with four examples as baselines, a small general-behaviour regression set, then merge the adapter into the base weights, confirm the merged model gives the same answers, and choose between merging and serving adapters.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Decide what counts as a correct answer
- Step 2: Base and tuned models on the same test rows
- Step 3: Check general behaviour for regressions
- Step 4: Merge the adapter, then check again
- Step 5: Merge or serve adapters?
- Check your understanding
- Apply it
- Review prompt
Lessons of LLM Fine-Tuning
- Should You Fine-Tune? A Decision Framework Concept · 20 min
- Building an Instruction Dataset the Model Can Learn From Worked example · 25 min
- LoRA and QLoRA: Training Millions of Parameters Instead of Billions Concept · 20 min
- Lab: Supervised Fine-Tuning with LoRA on a Single GPU Lab · 30 min
- Lab: Base vs Tuned on Held-Out Data Lab · 25 min
- Check: Fine-Tuning Trade-offs Knowledge check · 8 questions
What you will learn
- Evaluate the tuned model against the base model on held-out task metrics plus a regression check of general behaviour, then merge or serve the adapter.
Prerequisites: Transformer Architecture
01. Goal and setup
A falling validation loss says the adapter fits its validation data. It does not say whether the tuned model is better at the task than the base model with a good prompt, or whether it got worse at everything else. In this lab you answer both questions with numbers, then prepare the model for serving.
Work in the sft-lab folder of the SFT lab, with the same virtual environment active. You need its adapter/ folder and its train.jsonl and test.jsonl files. The test file holds 112 messages written in eight phrasings that neither training nor validation used. To keep the CPU time to a few minutes, the scripts score the first 48 of them; on a GPU, score all 112. Decoding is greedy everywhere, so every run gives the same answers on the same library versions.
ls adapter && wc -l < test.jsonladapter_config.json
adapter_model.safetensors
chat_template.jinja
README.md
tokenizer_config.json
tokenizer.json
training_args.bin
11202. Step 1: Decide what counts as a correct answer
Before you score any model, write the scoring rules as code, so that every model is judged the same way. evaluate.py defines three things. parse accepts a reply only if it is pure JSON with exactly the four keys, a string order id and product, one of the four allowed issues and a true or false urgent. This is schema validity: whether a program downstream could use the reply at all. score then measures per-field accuracy and exact match, the share of replies where all four fields are right. generate runs greedy decoding in left-padded batches, which is much faster than one message at a time.
"""Score a model on held-out messages: valid JSON, field accuracy and exact match."""
import json
import warnings
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from transformers.utils import logging
MODEL = "HuggingFaceTB/SmolLM2-135M-Instruct"
ISSUES = {"late", "damaged", "wrong_item", "refund"}
KEYS = ["order_id", "product", "issue", "urgent"]
logging.set_verbosity_error()
logging.disable_progress_bar()
warnings.filterwarnings("ignore", category=FutureWarning)
torch.set_num_threads(4)
def load(adapter=None, path=MODEL):
tokenizer = AutoTokenizer.from_pretrained(MODEL, padding_side="left")
model = AutoModelForCausalLM.from_pretrained(path, dtype=torch.float32)
if adapter:
from peft import PeftModel
model = PeftModel.from_pretrained(model, adapter)
return tokenizer, model.eval()
def generate(tokenizer, model, conversations, max_new_tokens=40, batch_size=16):
"""Greedy decoding for many conversations, in left-padded batches."""
replies = []
for i in range(0, len(conversations), batch_size):
batch = tokenizer.apply_chat_template(
conversations[i:i + batch_size], add_generation_prompt=True,
padding=True, return_tensors="pt", return_dict=True)
with torch.no_grad():
out = model.generate(**batch, max_new_tokens=max_new_tokens,
do_sample=False, pad_token_id=tokenizer.pad_token_id)
new = out[:, batch["input_ids"].shape[1]:]
texts = tokenizer.batch_decode(new, skip_special_tokens=True)
replies += [t.strip() for t in texts]
return replies
def parse(text):
"""The prediction as a dict if it is JSON with the right keys and types."""
try:
pred = json.loads(text)
except json.JSONDecodeError:
return None
if not isinstance(pred, dict) or sorted(pred) != sorted(KEYS):
return None
ok = (isinstance(pred["order_id"], str) and isinstance(pred["product"], str)
and pred["issue"] in ISSUES and isinstance(pred["urgent"], bool))
return pred if ok else None
def score(replies, rows):
preds = [parse(r) for r in replies]
n = len(rows)
result = {"valid": sum(p is not None for p in preds) / n,
"exact": sum(p == r["label"] for p, r in zip(preds, rows)) / n}
for k in KEYS:
result[k] = sum(p is not None and p[k] == r["label"][k]
for p, r in zip(preds, rows)) / n
return result
def show(name, result):
cells = " ".join(f"{k.replace('order_', '')} {v:.2f}" for k, v in result.items())
print(f"{name:14} {cells}")"""What counts as a valid reply? Four replies through parse()."""
from evaluate import parse
replies = [
'{"order_id":"48156","product":"rug","issue":"late","urgent":false}',
'{"order_id":"48156","product":"rug","issue":"lost","urgent":false}',
'{"order_id":48156,"product":"rug","issue":"late","urgent":"no"}',
'Sure! Here is the JSON: {"order_id":"48156","product":"rug"}',
]
for reply in replies:
print("valid" if parse(reply) else "invalid", "|", reply[:70])python check_parser.pyvalid | {"order_id":"48156","product":"rug","issue":"late","urgent":false}
invalid | {"order_id":"48156","product":"rug","issue":"lost","urgent":false}
invalid | {"order_id":48156,"product":"rug","issue":"late","urgent":"no"}
invalid | Sure! Here is the JSON: {"order_id":"48156","product":"rug"}The second reply is valid JSON but uses an issue that does not exist, the third has a number where a string is expected and a word where a boolean is expected, and the fourth wraps incomplete JSON in chat. A lenient scorer that searched for the first { would count some of these as successes and hide exactly the failures that break a production system.
03. Step 2: Base and tuned models on the same test rows
compare.py scores three set-ups on the same 48 test rows with the same system message. The base model zero-shot gets only the instructions. The base model 4-shot also gets one solved training example for each issue, which is the best cheap prompt baseline. The tuned model is the base model with the adapter, given only the instructions, as it will be in production. Expect the run to take a few minutes on a CPU.
"""Base model (zero-shot and 4-shot) against base + adapter, on the same test rows."""
import json
from evaluate import generate, load, score, show
N = 48 # the first 48 test rows keep the CPU run short
rows = [json.loads(line) for line in open("test.jsonl")][:N]
train = [json.loads(line) for line in open("train.jsonl")]
shots = [] # one training example per issue, as few-shot examples
for issue in ["late", "damaged", "wrong_item", "refund"]:
shots.append(next(r for r in train if r["label"]["issue"] == issue))
def few_shot(row):
turns = [row["prompt"][0]]
for s in shots:
turns += [s["prompt"][1], s["completion"][0]]
return turns + [row["prompt"][1]]
tokenizer, base = load()
show("base 0-shot", score(generate(tokenizer, base, [r["prompt"] for r in rows]), rows))
show("base 4-shot", score(generate(tokenizer, base, [few_shot(r) for r in rows]), rows))
tokenizer, tuned = load(adapter="adapter")
replies = generate(tokenizer, tuned, [r["prompt"] for r in rows])
show("tuned 0-shot", score(replies, rows))
with open("tuned_replies.json", "w") as f:
json.dump(replies, f)python compare.pybase 0-shot valid 0.00 exact 0.00 id 0.00 product 0.00 issue 0.00 urgent 0.00
base 4-shot valid 0.96 exact 0.17 id 0.94 product 0.75 issue 0.50 urgent 0.38
tuned 0-shot valid 0.98 exact 0.79 id 0.94 product 0.96 issue 0.94 urgent 0.85Zero-shot, the base model never produces a valid reply. With four examples it produces valid JSON 96% of the time and copies the order id well, but it gets the issue right only half the time and the urgency flag even less often, so only 17% of replies are fully correct. The tuned model reaches 79% exact match with a short prompt, and its weakest field is still urgent, at 85%. That is a large, real gain, measured on phrasings it never saw.
Be careful with what 48 examples can tell you. A difference of one or two replies is about 2–4 points, so small gaps between configurations would need the full test set, or a confidence interval such as a bootstrap, before you trust them. A gain from 17% to 79% does not.
04. Step 3: Check general behaviour for regressions
Training on a narrow task can damage what the model could do before, an effect called catastrophic forgetting. A tuned model can also start to apply the trained format where it does not belong. So keep a small regression set: ordinary requests with checkable answers, plus, for a real assistant, the safety behaviour you rely on, such as refusals. regression.py asks the base and the tuned model eight simple questions without the extraction system message and prints the result of every check side by side.
"""Has narrow tuning damaged general behaviour? A small check set, base vs tuned."""
from evaluate import generate, load
CHECKS = [ # (prompt, a word the answer must contain)
("What is the capital of France? Answer in one word.", "paris"),
("What is 12 plus 7? Answer with a number only.", "19"),
("Translate 'thank you' into French.", "merci"),
("What colour is the sky on a clear day? One word.", "blue"),
("Name the planet we live on. One word.", "earth"),
("Complete the sentence: the opposite of hot is", "cold"),
("How many days are in a week? Answer with a number.", "7"),
("Spell the word 'cat' backwards.", "tac"),
]
conversations = [[{"role": "user", "content": prompt}] for prompt, _ in CHECKS]
results = {}
for name, adapter in [("base", None), ("tuned", "adapter")]:
tokenizer, model = load(adapter=adapter)
replies = generate(tokenizer, model, conversations, max_new_tokens=24)
results[name] = [(word in r.lower(), r) for r, (_, word) in zip(replies, CHECKS)]
print(f"{'check':36} {'base':5} {'tuned':5} tuned reply")
for i, (prompt, _) in enumerate(CHECKS):
(base_ok, _), (tuned_ok, reply) = results["base"][i], results["tuned"][i]
marks = f"{'ok' if base_ok else '-':5} {'ok' if tuned_ok else '-':5}"
print(f"{prompt[:35]:36} {marks} {reply[:28]!r}")
for name, rows in results.items():
print(f"{name}: {sum(ok for ok, _ in rows)}/{len(CHECKS)} passed, "
f"{sum(r.startswith('{') for _, r in rows)} replied with JSON")python regression.pycheck base tuned tuned reply
What is the capital of France? Answ ok ok 'Paris'
What is 12 plus 7? Answer with a nu - - '"12 + 7 equals 29'
Translate 'thank you' into French. ok - '"Bonjour"'
What colour is the sky on a clear d ok - '"Sky"'
Name the planet we live on. One wor - ok '"Earth"'
Complete the sentence: the opposite ok ok '"The opposite of hot is cold'
How many days are in a week? Answer - ok '"A week is 7 days"'
Spell the word 'cat' backwards. - - '"cat backwards"'
base: 4/8 passed, 0 replied with JSON
tuned: 4/8 passed, 0 replied with JSONThe totals are equal, but the table is not: the tuned model lost the French translation and the sky colour, and gained the planet and the days of the week. It also wraps most answers in a stray double quote, a trace of the JSON strings it was trained on. Nothing here is serious for an extraction service that always sends its own system message, but you only know that because you looked at each check. For a real model, use a larger set (tens to hundreds of prompts), decide in advance how many regressions you accept, and read the changed answers, not just the totals.
05. Step 4: Merge the adapter, then check again
To serve one tuned model, you can merge the adapter: merge_and_unload adds the scaled low-rank update to each targeted weight and returns a plain Transformers model with no PEFT layers, so inference runs at exactly the cost of the base model. The merge must happen on base weights in floating point. This lab trained on a float32 base, so it merges in float32. After a QLoRA run, load the base again in 16-bit (bf16), not in 4-bit, apply the adapter there and merge. Whatever the precision, a merged model is a new artifact, so merge.py reloads it from disk as a plain model and scores it again.
"""Merge the adapter into the base weights, then check that nothing changed."""
import json
import os
import torch
from evaluate import generate, load, score, show
tokenizer, tuned = load(adapter="adapter")
merged = tuned.merge_and_unload() # W + (alpha / r) * B @ A, adapter removed
merged.save_pretrained("merged")
tokenizer.save_pretrained("merged")
rows = [json.loads(line) for line in open("test.jsonl")][:48]
tokenizer, reloaded = load(path="merged") # a plain model, no PEFT needed
replies = generate(tokenizer, reloaded, [r["prompt"] for r in rows])
before = json.load(open("tuned_replies.json"))
same = sum(a == b for a, b in zip(replies, before))
print(f"replies identical to base + adapter: {same}/{len(rows)}")
show("merged 0-shot", score(replies, rows))
def size_mb(folder, name):
return os.path.getsize(os.path.join(folder, name)) / 1e6
print(f"adapter file {size_mb('adapter', 'adapter_model.safetensors'):.1f} MB, "
f"merged model {size_mb('merged', 'model.safetensors'):.1f} MB")python merge.pyreplies identical to base + adapter: 48/48
merged 0-shot valid 0.98 exact 0.79 id 0.94 product 0.96 issue 0.94 urgent 0.85
adapter file 19.6 MB, merged model 538.1 MBEvery reply is identical and so are the scores. The cost shows in the size: the merged model is a full 538 MB copy in float32, against 19.6 MB for the adapter.
06. Step 5: Merge or serve adapters?
Merging suits one tuned behaviour that you serve on its own: it needs no PEFT at serving time and works with any server that loads a plain model. Keeping adapters separate suits many tuned behaviours on the same base, for example one per customer or per task. Serving engines such as vLLM load one copy of the base and apply a different small adapter per request, so ten adapters cost little more memory than one. The command below shows the vLLM form on a GPU server; it is not run in this CPU lab. Requests then name extractor as their model.
vllm serve HuggingFaceTB/SmolLM2-135M-Instruct \
--enable-lora --lora-modules extractor=./adapter --max-lora-rank 16Before you publish either form, complete the model card, the README.md that PEFT already wrote into adapter/: the base model and its revision, the training data and how it was split, the settings of the run, the held-out results against the baselines, the regression results and the known weaknesses, such as the weaker urgent field and the stray quotes.
07. Check your understanding
08. Apply it
For your project, run this evaluation on your QLoRA adapter with the full held-out set: schema validity, per-field accuracy and exact match against few-shot prompting of the base model, plus a general-ability regression set of at least 30 prompts with your accepted number of regressions written down in advance. Merge in bf16 if you will serve a single model, re-run the same scripts on the merged model, and publish the adapter or the merged model with a completed model card.
09. Review prompt
Without looking back, answer in your own words:
- What are schema validity, per-field accuracy and exact match, and why report all three?
- Why is the base model with four examples a fairer baseline than the base model zero-shot?
- What is catastrophic forgetting, and what does a regression set check?
- How do you merge an adapter trained with QLoRA, and what do you do with the merged model before you ship it?
- When would you serve separate adapters instead of a merged model?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.