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

Project: Improve

One more change.

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

Version two is better, but it still mixes up some questions. The training loss was still falling, when training stopped. That's a sign the model could learn more. So our next change is more epochs.

  • Still some mix-ups
  • Loss still falling
  • Try more epochs

Version three: three epochs

Here's the only change. Epochs becomes three, and the output folder is tickets v three. Everything else is the same. Three epochs takes about three times as long, so we trained it ahead of time.

train.pypython
from transformers import AutoTokenizer, AutoModelForCausalLM
from peft import LoraConfig
from trl import SFTTrainer, SFTConfig
from chat import data

NAME = "HuggingFaceTB/SmolLM2-135M-Instruct"
EPOCHS, OUT = 3, "tickets-v3"
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=OUT, num_train_epochs=EPOCHS, learning_rate=2e-4,
                 per_device_train_batch_size=8, save_strategy="no", report_to="none")
trainer = SFTTrainer(model=model, args=args, train_dataset=data["train"],
                     processing_class=tok, peft_config=lora)
result = trainer.train()
print(f"trained {OUT}: {result.global_step} steps, loss {result.training_loss:.3f}, "
      f"{result.metrics['train_runtime']:.0f} seconds")
trainer.save_model(OUT)

All three versions

Now we score all three versions, on the same test set. Run it. Version three scores ninety seven percent! That's eleven points better than where we started.

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),
                        ("tickets-v3", 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%'}
tickets-v3   {'valid_json': '100%', 'correct': '97%'}
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')
shutil.copytree('/Users/hussain/Docker Complete Course/shared-data/ft_cache/tickets-v3', 'tickets-v3')
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%}"}

Version three's mistakes

Let's check version three's mistakes. Run it. Only two left. But look. Both are messages about reserving a copy. And the model invented reserve copy. Our training data has no messages about reserving. More epochs can't fix missing data.

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-v3")
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        -> reserve_copy Good morning. Can I reserve a copy of Beloved? Thank
stock        -> reserve_copy Hi, Can I reserve a copy of Dune?
2 stock -> reserve_copy
Also uses _setup.py
import shutil
shutil.copytree('/Users/hussain/Docker Complete Course/shared-data/ft_cache/tickets-v3', 'tickets-v3')
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 next?

There are two good fixes. First, add training messages about reserving books, labelled as stock. Second, check every answer in code. If the intent isn't in the allowed list, send the message to a person. We'll add that safety check in our app.

keyvalue
Data fixadd 'reserve' examples
Code fixvalidate the intent
Fallbacksend to a person
Rulenever trust output blindly

Summary

Let's recap. Three epochs raised the score to ninety seven percent. The last mistakes come from missing data. And code checks protect us from invented intents. Next, we merge and save the final model.

Key takeaways
  • 3 epochs: 97%
  • Missing data: reserve
  • Validate in code
Next up: Project: Merge and Save — the final model