Sub topic 7
Preparing data and chat templates
This chapter assumes you can run a Hugging Face transformers model for inference and that you know basic Python. It covers how to turn raw examples into the format that supervised fine-tuning expects, and why the chat template matters more than most beginners expect.
What the trainer needs
Supervised fine-tuning (SFT) teaches the model to produce a target answer for a given prompt. Each training example is therefore a prompt paired with a desired response. TRL's SFTTrainer accepts two common layouts.
| Layout | Record shape | Typical use |
|---|---|---|
| Conversational | `{"messages": [{"role": ..., "content": ...}, ...]}` | Chat and instruct models |
| Plain text | `{"text": "..."}` | Base models, completion tasks |
For an instruct model such as Qwen2.5-0.5B-Instruct, use the conversational layout. The trainer applies the model's chat template for you.
Why chat templates matter
A chat model was trained on text where roles are marked by special tokens. The chat template is a function stored with the tokenizer. It converts a list of messages into the exact string the model expects. If your fine-tuning data uses a different format from the one the model saw in training, the adapter has to learn both the new task and the new format. Worse, at inference you may build the prompt differently from training, and quality drops with no error message.
You can inspect a template directly.
from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct")
messages = [
{"role": "user", "content": "Summarize: LoRA trains small low-rank matrices."},
{"role": "assistant", "content": "LoRA adapts a model by training only small low-rank matrices."},
]
text = tok.apply_chat_template(messages, tokenize=False)
print(text)The output wraps each turn in markers such as <|im_start|> and <|im_end|>. Different model families use different markers, so never copy a template from another model.
At inference time, you format only the prompt and ask the template to open the assistant turn.
prompt = tok.apply_chat_template(
messages[:1], tokenize=False, add_generation_prompt=True
)
print(prompt)add_generation_prompt=True appends the start of the assistant turn, so the model continues with its answer. Training data contains the full conversation. Inference prompts end where the answer begins.
Building a dataset
The datasets library turns a list of dictionaries into a dataset. If your source is a CSV or JSON file, map each row to the messages structure.
from datasets import Dataset
rows = [
{"question": "What does LoRA stand for?", "answer": "Low-Rank Adaptation."},
{"question": "What does PEFT stand for?", "answer": "Parameter-Efficient Fine-Tuning."},
{"question": "What is rank in LoRA?", "answer": "The inner dimension of the two small matrices."},
{"question": "Which matrix starts at zero?", "answer": "Matrix B."},
]
def to_messages(row):
return {
"messages": [
{"role": "user", "content": row["question"]},
{"role": "assistant", "content": row["answer"]},
]
}
ds = Dataset.from_list(rows).map(to_messages, remove_columns=["question", "answer"])
split = ds.train_test_split(test_size=0.25, seed=42)
train_ds, eval_ds = split["train"], split["test"]
print(train_ds[0])
print(len(train_ds), len(eval_ds))The split holds out examples the adapter never trains on. You will need them in the evaluation chapter, so create the split now and fix the seed so it stays the same between runs.
Quality checks before training
Data problems cause more failed runs than hyperparameters do. Check these before you start:
- Consistent roles. Every example alternates
userandassistant, and the final turn is the assistant's answer. - No empty or duplicated content. Duplicates in both splits make evaluation look better than it is.
- Sequence length. Examples longer than the trainer's maximum length are truncated, which can cut off the answer you wanted the model to learn.
- No double templating. If you pre-apply the template and store the result as
text, the trainer must not apply it again. Pick one place to do it. - Representative answers. The model imitates the style, length and tone of your responses, including their mistakes.
A few hundred clean, varied examples often beat thousands of noisy ones for a narrow task.
Exercise
You fine-tuned an instruct model on data you formatted by hand with your own "User:" and "Assistant:" labels. At inference you use the tokenizer's chat template, and answers are poor. What is the likely cause, and what is the fix?
Show answer
The training format and the inference format differ, so the adapter learned patterns the model never sees at inference. Store the data as messages records and let the tokenizer's chat template format both training and inference, with add_generation_prompt=True for prompts. Then retrain.