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

Project: Dataset

A better system message.

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

Remember, the model learns its task together with the system message. So when we change the system message, we must train again, with the new one.

  • The system message is part of the task
  • Change it, then retrain
  • Same message in use

chat.py, version two

Here's the new chat dot p y. Intents is the list of allowed intents. The system message now ends with, the intent must be one of, and then the list. Everything else stays the same. The same messages, and the same JSON answers.

chat.pypython
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"])

Checking the new data

Let's check it. We print the new system message, the sizes of both splits, and the first answer. Run it. The system message lists all five intents. Five hundred and twenty seven training examples, and seventy seven for testing. And the answers are unchanged.

app.pypython
import textwrap
from chat import SYSTEM, data

print(textwrap.fill(SYSTEM, 80))
print()
print("train:", len(data["train"]), " test:", len(data["test"]))
print(data["train"][0]["completion"][0]["content"])
Output
Read the customer's message. Reply with JSON: the intent and the book. The
intent must be one of: order_status, return, price, stock, complaint.

train: 527  test: 77
{"intent": "complaint", "book": "Dune"}
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 we didn't change

Notice what we didn't do. We didn't add the test set's phrasings to the training data. That would make our score look better, but it would be cheating. The test set must stay unseen, so it tells us the truth.

keyvalue
Changedthe system message
Unchangedmessages and answers
Not addedtest phrasings
Whytest must stay unseen

Summary

Let's recap. Version two lists the allowed intents in the system message. The data is otherwise unchanged. And the test set stays unseen. Next, we train the new model.

Key takeaways
  • Intents in the system message
  • Same examples
  • Test set unseen
Next up: Project: Train — version two