AI Hints
Home›Fine-Tuning LLMs Tutorial›Project: Plan, Data and Baseline
Fine-Tuning LLMs · Lesson 104 of 120

Project: Baseline

Where we start.

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

Before changing anything, we measure where we start. This is the baseline. Every later result is compared against it.

  • Measure first
  • The baseline
  • Compare everything to it

Baseline and predicted intents

We load our current model, and score it on the test set. Then we count every intent the model predicts. Run it. Eighty six percent correct, as before. Most predictions are spread across our five intents. But look at the bottom. Reserve. Three times, the model invented an intent that doesn't exist.

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
from score import score

NAME = "HuggingFaceTB/SmolLM2-135M-Instruct"
tok = AutoTokenizer.from_pretrained(NAME)
model = PeftModel.from_pretrained(AutoModelForCausalLM.from_pretrained(NAME), "ticket-lora")
test = load_dataset("json", data_files="tickets_test.jsonl")["train"]
print("baseline:", score(model, tok, test))
predicted = Counter(json.loads(ask(model, tok, m))["intent"] for m in test["message"])
for intent, n in predicted.most_common():
    print(f"   {intent:13} {n:3}")
Output
baseline: {'valid_json': '100%', 'correct': '86%'}
   complaint      17
   price          15
   return         15
   stock          14
   order_status   13
   reserve         3
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%}"}

Our one change

So here's our one change. The model never sees the allowed intents. It has to guess them from the examples. Let's list them, right in the system message. Then the model always knows its choices.

keyvalue
Probleminvented intents
Causeallowed intents never shown
Changelist them in the system message
Expectno invented intents

Summary

Let's recap. The baseline is eighty six percent correct. It sometimes invents an intent. And our one change is to list the allowed intents, in the system message. Next, we update the dataset.

Key takeaways
  • Baseline: 86%
  • Invented: reserve
  • Change: list the intents
Next up: Project: Dataset — a better system message