AI Hints
Home›Fine-Tuning LLMs Tutorial›Project: Train, Evaluate and Improve
Fine-Tuning LLMs · Lesson 107 of 120

Project: Evaluate

Did it work?.

⏱ 2 min read▶ Video at 2:42:56🎓 Free
Watch this lesson in the Fine-Tuning LLMs courseWatch on YouTube ↗Full Fine-Tuning LLMs course

The moment of truth. Did listing the intents help? We'll score both models, on the same test set.

  • The moment of truth
  • Did it help?
  • Same test set

Version one vs version two

Each model must use the system message it was trained with. So version one gets the old message, and version two gets the new one. We set it, then score each model. Run it. Version two scores ninety percent. Up from eighty six.

app.pypython
from transformers import AutoTokenizer, AutoModelForCausalLM
from peft import PeftModel
from datasets import load_dataset
from score import score
import ask, chat

NAME = "HuggingFaceTB/SmolLM2-135M-Instruct"
OLD_SYSTEM = "Read the customer's message. Reply with JSON: the intent and the book."
tok = AutoTokenizer.from_pretrained(NAME)
test = load_dataset("json", data_files="tickets_test.jsonl")["train"]
for adapter, system in [("ticket-lora", OLD_SYSTEM), ("tickets-v2", chat.SYSTEM)]:
    ask.SYSTEM = system                    # each model gets the system message it was trained with
    model = PeftModel.from_pretrained(AutoModelForCausalLM.from_pretrained(NAME), adapter)
    print(f"{adapter:12} {score(model, tok, test)}")
Output
ticket-lora  {'valid_json': '100%', 'correct': '86%'}
tickets-v2   {'valid_json': '100%', 'correct': '90%'}
Also uses _setup.py
import shutil
shutil.copytree('/Users/hussain/Docker Complete Course/shared-data/ft_cache/ticket-lora', 'ticket-lora')
shutil.copytree('/Users/hussain/Docker Complete Course/shared-data/ft_cache/tickets-v2', 'tickets-v2')
Also uses chat.py
import json
from datasets import load_dataset

INTENTS = ["order_status", "return", "price", "stock", "complaint"]
SYSTEM = ("Read the customer's message. Reply with JSON: the intent and the book. "
          "The intent must be one of: " + ", ".join(INTENTS) + ".")

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 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 is still wrong?

Now let's look at version two's mistakes, with our error analysis script. Run it. No more invented intents. Every prediction is one of our five. Most remaining mistakes are about orders. Has it been posted yet, gets confused with stock.

app.pypython
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), "tickets-v2")
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)
Output
stock        -> order_status Good morning. Can I reserve a copy of Beloved? Thank
order_status -> complaint    Good morning. Any news on my Dune order? Please help
price        -> stock        Hi, Is Beloved on sale at the moment?
return       -> stock        The Hobbit has torn pages, can I swap it? Please hel
order_status -> complaint    Good morning. Any news on my Dune order? Cheers
order_status -> stock        Hello! Has Dune been posted yet? Cheers
order_status -> stock        has circe been posted yet? thanks.
order_status -> stock        Hey, Has The Hobbit been posted yet?
3 order_status -> stock
2 order_status -> complaint
1 stock -> order_status
1 price -> stock
1 return -> stock
Also uses _setup.py
import shutil
shutil.copytree('/Users/hussain/Docker Complete Course/shared-data/ft_cache/tickets-v2', 'tickets-v2')
Also uses chat.py
import json
from datasets import load_dataset

INTENTS = ["order_status", "return", "price", "stock", "complaint"]
SYSTEM = ("Read the customer's message. Reply with JSON: the intent and the book. "
          "The intent must be one of: " + ", ".join(INTENTS) + ".")

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 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%}"}

Summary

Let's recap. Version two scores ninety percent, up from eighty six. Listing the intents stopped the invented intents. And the remaining mistakes are mostly about orders. Next, we try to improve it further.

Key takeaways
  • 90%, up from 86%
  • No invented intents
  • Order questions still hard
Next up: Project: Improve — one more change