Exact Match and Valid JSON
Two numbers that matter.
For our ticket task, two numbers matter most. How often is the reply valid JSON? And how often is it exactly right? Let's write a scoring function, that we'll use for the rest of the course.
- Two numbers matter
- Valid JSON, and correct
- A reusable scorer
score.py
Here's score dot p y. For each test row, we ask the model. JSON loads tries to parse the reply. If that fails, or the reply isn't a JSON object, we skip to the next row. Otherwise, it's valid. And if the intent and the book both match, it's correct. Finally, we turn the counts into percentages.
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%}"}Base vs fine-tuned
Now we score two models on the seventy seven test tickets. First, the original base model. Then the same model, with our LoRA adapter. Run it. The base model never once replies with JSON. Our fine-tuned model is always valid JSON, and eighty six percent correct.
from transformers import AutoTokenizer, AutoModelForCausalLM
from peft import PeftModel
from datasets import load_dataset
from score import score
NAME = "HuggingFaceTB/SmolLM2-135M-Instruct"
tok = AutoTokenizer.from_pretrained(NAME)
test = load_dataset("json", data_files="tickets_test.jsonl")["train"]
base = AutoModelForCausalLM.from_pretrained(NAME)
print("base model: ", score(base, tok, test))
tuned = PeftModel.from_pretrained(AutoModelForCausalLM.from_pretrained(NAME), "ticket-lora")
print("fine-tuned: ", score(tuned, tok, test))base model: {'valid_json': '0%', 'correct': '0%'}
fine-tuned: {'valid_json': '100%', 'correct': '86%'}Also uses _setup.py
import shutil
shutil.copytree('/Users/hussain/Docker Complete Course/shared-data/ft_cache/ticket-lora', 'ticket-lora')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%}"}Reading the numbers
Valid JSON tells us the model learned the format. Correct tells us it learned the task. One hundred, and eighty six, means the format is solved, but some answers are still wrong. Later, we'll look at those mistakes, and improve them.
| key | value |
|---|---|
| Valid JSON 100% | format: learned |
| Correct 86% | task: mostly learned |
| The gap | 14% wrong answers |
| Next step | look at the mistakes |
Summary
Let's recap. Score structured output with two numbers. Valid JSON, for the format. And correct, for the task. Our model gets one hundred, and eighty six percent. Next, perplexity.
Key takeaways- Valid JSON %
- Correct %
- 100% and 86%