Error Analysis
Learn from the mistakes.
Eighty six percent correct means fourteen percent wrong. Which ones? And why? Reading the mistakes is the fastest way to improve a model.
- Fourteen percent wrong
- Which ones, and why?
- The fastest way to improve
Listing the mistakes
Here's our error analysis. For each test row, we ask the model, and parse its answer. If the intent is wrong, we count the kind of mistake, and print the message. If only the book is wrong, we count that too. Finally, we print the most common mistakes. Run it. Look at reserve. That's not one of our five intents! The model invented a new one, three times.
import json
from collections import Counter
from transformers import AutoTokenizer, AutoModelForCausalLM
from peft import PeftModel
from datasets import load_dataset
from ask import ask
NAME = "HuggingFaceTB/SmolLM2-135M-Instruct"
tok = AutoTokenizer.from_pretrained(NAME)
model = PeftModel.from_pretrained(AutoModelForCausalLM.from_pretrained(NAME), "ticket-lora")
mistakes = Counter()
for row in load_dataset("json", data_files="tickets_test.jsonl")["train"]:
got = json.loads(ask(model, tok, row["message"]))
if got["intent"] != row["intent"]:
mistakes[f'{row["intent"]} -> {got["intent"]}'] += 1
print(f'{row["intent"]:12} -> {got["intent"]:12} {row["message"][:52]}')
elif got["book"] != row["book"]:
mistakes["wrong book"] += 1
for kind, n in mistakes.most_common():
print(n, kind)stock -> reserve Good morning. Can I reserve a copy of Beloved? Thank order_status -> stock Good morning. Any news on my Dune order? Please help stock -> order_status Good morning. Will you get more copies of Circe? stock -> reserve Hi, Can I reserve a copy of Dune? price -> stock Hi, Is Beloved on sale at the moment? order_status -> complaint Hey, Is my Persuasion parcel on its way? Cheers stock -> price Will you get more copies of Rebecca? stock -> order_status Hello! Will you get more copies of Rebecca? stock -> reserve Hello! Can I reserve a copy of Dune? order_status -> stock has circe been posted yet? thanks. order_status -> stock Hey, Has The Hobbit been posted yet? 3 stock -> reserve 3 order_status -> stock 2 stock -> order_status 1 price -> stock 1 order_status -> complaint 1 stock -> price
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%}"}What the mistakes tell us
So what did we learn? The model never sees the list of allowed intents, so it invents new ones. Questions about restocking get confused with order status. And the test set uses some phrasings, that training never showed. All of these can be fixed.
| key | value |
|---|---|
| Invented intent | reserve, not allowed |
| Confused | restock vs order status |
| Unseen phrasing | new templates in test |
| Fix ideas | list intents, more data |
Turning errors into fixes
Each kind of mistake suggests a fix. List the allowed intents in the system message. Add training examples with the new phrasings. And train a little longer. In the project, we'll try these, and measure each one.
| key | value |
|---|---|
| Invented labels | list them in the prompt |
| Unseen phrasing | add examples |
| Underfitting | train longer |
| Always | measure each fix |
Summary
Let's recap. Print every mistake, and group them by kind. Look for patterns, like invented labels. And turn each pattern into a fix, that you can measure. Next, evaluation practice.
Key takeaways- Print the mistakes
- Group by kind
- One fix per pattern