An Evaluation Loop
Score every checkpoint.
So far, we scored the model once, after training. But it's more useful to watch the real score while training runs. Then we can see when the model stops improving.
- Scored once, after training
- Watch it during training
- See when it stops improving
What is a callback?
The trainer lets us plug in our own code, at key moments. This is called a callback. A callback is a class, with methods like on evaluate, or on epoch end. The trainer calls them for us, at the right time.
| key | value |
|---|---|
| Callback | your code, run by the trainer |
| on_evaluate | after each evaluation |
| on_epoch_end | after each epoch |
| Use | extra metrics, logging |
Scoring during training
Here's our callback. We take the first twenty test tickets, to keep it quick. On evaluate runs after each evaluation. It scores the model, and prints the step, the eval loss, and the score. Then it puts the model back into training mode. Add callback plugs it in. Run it. As training continues, the eval loss falls. And the real score climbs, from sixty, to eighty five percent.
from transformers import TrainerCallback
from datasets import load_dataset
from sft import trainer, tok
from score import score
sample = load_dataset("json", data_files="tickets_test.jsonl")["train"].select(range(20))
class ScoreCallback(TrainerCallback):
def on_evaluate(self, args, state, control, model=None, metrics=None, **kwargs):
result = score(model, tok, sample)
print(f"step {state.global_step:3} eval loss {metrics['eval_loss']:.3f} {result}")
model.train() # back to training mode
trainer.add_callback(ScoreCallback())
trainer.train()step 22 eval loss 0.133 {'valid_json': '100%', 'correct': '60%'}
step 44 eval loss 0.035 {'valid_json': '100%', 'correct': '75%'}
step 66 eval loss 0.025 {'valid_json': '100%', 'correct': '85%'}Also uses chat.py
import json
from datasets import load_dataset
SYSTEM = "Read the customer's message. Reply with JSON: the intent and the book."
def to_example(row):
answer = json.dumps({"intent": row["intent"], "book": row["book"]})
return {"prompt": [{"role": "system", "content": SYSTEM},
{"role": "user", "content": row["message"]}],
"completion": [{"role": "assistant", "content": answer}]}
data = load_dataset("json", data_files={"train": "tickets_train.jsonl",
"test": "tickets_test.jsonl"})
data = data.map(to_example, remove_columns=["message", "intent", "book"])Also uses ask.py
from chat import SYSTEM
def ask(model, tok, message):
model.eval() # switch off training-only behaviour
messages = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": message}]
ids = tok.apply_chat_template(messages, add_generation_prompt=True,
return_dict=True, return_tensors="pt")
out = model.generate(**ids, max_new_tokens=30, do_sample=False)
return tok.decode(out[0][ids["input_ids"].shape[1]:], skip_special_tokens=True)Also uses sft.py
from transformers import AutoTokenizer, AutoModelForCausalLM
from peft import LoraConfig
from trl import SFTTrainer, SFTConfig
from chat import data
NAME = "HuggingFaceTB/SmolLM2-135M-Instruct"
tok = AutoTokenizer.from_pretrained(NAME)
model = AutoModelForCausalLM.from_pretrained(NAME)
lora = LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05,
target_modules="all-linear", task_type="CAUSAL_LM")
args = SFTConfig(output_dir="ticket-lora", num_train_epochs=1, learning_rate=2e-4,
per_device_train_batch_size=8, logging_steps=11,
eval_strategy="steps", eval_steps=22,
save_strategy="no", report_to="none")
trainer = SFTTrainer(model=model, args=args, train_dataset=data["train"],
eval_dataset=data["test"], processing_class=tok, peft_config=lora)Also uses score.py
import json
from ask import ask
def score(model, tok, rows):
valid = correct = 0
for row in rows:
reply = ask(model, tok, row["message"])
try:
answer = json.loads(reply)
except json.JSONDecodeError:
continue # not JSON: neither valid nor correct
if not isinstance(answer, dict):
continue # JSON, but not an object
valid += 1
if answer.get("intent") == row["intent"] and answer.get("book") == row["book"]:
correct += 1
n = len(rows)
return {"valid_json": f"{valid / n:.0%}", "correct": f"{correct / n:.0%}"}Loss and score together
Notice something. Between step forty four and sixty six, the loss only fell a little. But the score rose by ten points. Small changes in loss can matter a lot for the real task. That's why we measure both.
| key | value |
|---|---|
| Step 44 → 66 | loss: 0.035 → 0.025 |
| Score | 75% → 85% |
| Lesson | loss and score can differ |
| So | measure both |
Summary
Let's recap. A callback runs your code during training. On evaluate is perfect for scoring. And the real score can change more than the loss suggests. Next, using a model as a judge.
Key takeaways- TrainerCallback
- on_evaluate
- Measure loss and score