AI Hints
Home›Fine-Tuning LLMs Tutorial›Instruction Data
Fine-Tuning LLMs · Lesson 47 of 120

Build a Chat Dataset

From rows to conversations.

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

Our data is rows, with a message, an intent, and a book. We need to turn each row into a small conversation, with the JSON answer we want. One map call will do it.

  • Rows: message, intent, book
  • Turn each into a conversation
  • One map call

chat.py

Here's chat dot p y. First, the system message. It tells the model its job. The to example function builds the answer, as JSON, with json dumps. The prompt is the system message, and the customer's message, as the user. The completion is the assistant's answer. Then we load both files, and map to example over every row, removing the old columns.

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

One training example

Let's print the new dataset, and one example, role by role. Run it. Each dataset now has two columns, prompt, and completion. The prompt has the system message, and the customer's message. And the completion is exactly the JSON we want the model to write.

app.pypython
from chat import data

print(data)
example = data["train"][0]
print("PROMPT:")
for msg in example["prompt"]:
    print(f"  {msg['role']:9} {msg['content']}")
print("COMPLETION:")
print(f"  {example['completion'][0]['role']:9} {example['completion'][0]['content']}")
Output
DatasetDict({
    train: Dataset({
        features: ['prompt', 'completion'],
        num_rows: 527
    })
    test: Dataset({
        features: ['prompt', 'completion'],
        num_rows: 77
    })
})
PROMPT:
  system    Read the customer's message. Reply with JSON: the intent and the book.
  user      Hello! The driver was rude when delivering Dune.
COMPLETION:
  assistant {"intent": "complaint", "book": "Dune"}
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,
                 save_strategy="no", report_to="none")
trainer = SFTTrainer(model=model, args=args, train_dataset=data["train"],
                     processing_class=tok, peft_config=lora)

Keep the system message short

Notice our system message is short. It will be sent with every request, forever, so every word costs time and money. After fine-tuning, the model learns the task from the examples. The system message just reminds it which task to do.

keyvalue
Sentwith every request
Every wordcosts time and money
Fine-tuned modellearned from examples
System messagea short reminder

Summary

Let's recap. Each row becomes a prompt, and a completion. The prompt holds the system and user messages. The completion holds the JSON answer. Next, making sure the model learns only from the answer.

Key takeaways
  • to_example(row)
  • prompt: system + user
  • completion: JSON answer
Next up: Train on Answers Only — completion-only loss