Sub topic 7
Preparing data and chat templates
This chapter assumes you can run a Hugging Face transformers model for inference and use the datasets library at a basic level. It also assumes you know that a causal language model predicts the next token. By the end you should be able to turn raw examples into correctly templated training text. You should also be able to check that the loss is computed only on the tokens you want the model to learn.
Why formatting decides the result
A LoRA adapter learns whatever pattern the training text shows. The pattern includes the layout of the text, not only the content. An instruction-tuned model such as Qwen2.5-0.5B-Instruct was trained on one specific layout. The layout uses special tokens that mark where each role starts and ends. If you train with a different layout, the adapter must learn the new one and also learn your task. That wastes capacity and often produces models that ramble or never stop.
The chat template is the rule that turns a list of messages into one string with those special tokens. It ships with the tokenizer, so you should always use it instead of writing the string by hand.
Dataset shapes
TRL's SFTTrainer accepts several record shapes. Pick the one that matches your data.
| Shape | Example fields | Template applied by trainer | Typical use |
|---|---|---|---|
| Conversational | `messages` (list of role/content dicts) | Yes | Chat and assistant behavior |
| Prompt-completion | `prompt`, `completion` | Yes, if both are message lists | Single-turn tasks, loss on completion only |
| Plain text | `text` | No, text is used as is | Continued pretraining, pre-rendered data |
For an Instruct model, the conversational shape is the safest default. The trainer applies the model's own template, so the training text matches what the model saw during its original tuning.
Looking at what the template produces
Render one example and read it. This takes seconds and catches most formatting bugs.
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 matrices."},
]
print(tok.apply_chat_template(messages, tokenize=False))
print("---- inference prompt ----")
print(tok.apply_chat_template(messages[:-1], tokenize=False, add_generation_prompt=True))For Qwen the output uses <|im_start|> and <|im_end|> markers around each role. The template also inserts a default system message when you give none. The second print shows the generation prompt. It ends with <|im_start|>assistant and a newline, so the model's next token is the first token of the reply.
The two renderings differ by exactly the assistant turn. This fact is the basis of the masking technique below.
From raw records to a training set
Real data rarely arrives as messages. The following script converts simple question-answer records. It drops empty and duplicate rows, removes examples that are too long, and holds out a validation split.
from datasets import Dataset
from transformers import AutoTokenizer
MODEL_ID = "Qwen/Qwen2.5-0.5B-Instruct"
MAX_TOKENS = 512
tok = AutoTokenizer.from_pretrained(MODEL_ID)
raw = [
{"question": "What does LoRA stand for?", "answer": "Low-Rank Adaptation."},
{"question": "What does LoRA stand for?", "answer": "Low-Rank Adaptation."},
{"question": "Which matrix starts at zero?", "answer": "B, so the adapter starts as a no-op."},
{"question": "What is rank?", "answer": ""},
{"question": "What does alpha control?", "answer": "It scales the update by alpha divided by r."},
{"question": "Name one target module.", "answer": "q_proj is a common choice."},
{"question": "Why freeze the base weights?", "answer": "It saves optimizer memory and keeps the base intact."},
{"question": "What is QLoRA?", "answer": "LoRA training on top of a 4-bit quantized base model."},
]
seen = set()
records = []
for r in raw:
q, a = r["question"].strip(), r["answer"].strip()
if not q or not a or (q, a) in seen:
continue
seen.add((q, a))
records.append({"messages": [
{"role": "user", "content": q},
{"role": "assistant", "content": a},
]})
ds = Dataset.from_list(records)
def n_tokens(example):
text = tok.apply_chat_template(example["messages"], tokenize=False)
return {"n_tokens": len(tok(text, add_special_tokens=False)["input_ids"])}
ds = ds.map(n_tokens).filter(lambda e: e["n_tokens"] <= MAX_TOKENS)
ds = ds.remove_columns("n_tokens")
splits = ds.train_test_split(test_size=0.2, seed=42)
train_ds, eval_ds = splits["train"], splits["test"]
print(len(train_ds), len(eval_ds))Notes on this code:
- It counts tokens on the rendered text, because the template adds tokens of its own.
add_special_tokens=Falseavoids counting a second beginning-of-sequence token. The template already includes any special tokens it needs.- The fixed
seedmakes the split reproducible. Reuse the same split when you compare the adapter with the base model in a later chapter.
Which tokens carry the loss
By default, supervised fine-tuning computes the loss on every token, including the user's prompt. Often that is not what you want. If your prompts are long and your answers are short, most of the gradient goes to memorizing prompts. Masking sets the label of a token to -100, which PyTorch's cross-entropy loss ignores.
Recent TRL versions offer options for this in SFTConfig. completion_only_loss applies to prompt-completion data. assistant_only_loss=True applies to conversational data, and it requires a chat template that marks assistant spans. Many templates do not, so check your installed version's documentation before relying on it.
You can also build the labels yourself. This works with any template where the prompt rendering is a prefix of the full rendering.
from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct")
def encode_with_mask(messages):
prompt_text = tok.apply_chat_template(
messages[:-1], tokenize=False, add_generation_prompt=True
)
full_text = tok.apply_chat_template(messages, tokenize=False)
assert full_text.startswith(prompt_text), "prompt is not a prefix of the full text"
prompt_ids = tok(prompt_text, add_special_tokens=False)["input_ids"]
full_ids = tok(full_text, add_special_tokens=False)["input_ids"]
labels = [-100] * len(prompt_ids) + full_ids[len(prompt_ids):]
return {"input_ids": full_ids, "labels": labels}
example = encode_with_mask([
{"role": "user", "content": "What is rank?"},
{"role": "assistant", "content": "The number of independent rows in a matrix."},
])
trained = [t for t in example["labels"] if t != -100]
print(len(example["input_ids"]), len(trained))
print(repr(tok.decode(trained)))The decoded text should contain only the assistant reply and the closing <|im_end|> marker. Training on that end marker is what teaches the model to stop.
Edge cases that cause silent damage
- Duplicate special tokens. If you render with
apply_chat_template(tokenize=False)and then tokenize with the defaultadd_special_tokens=True, some tokenizers add a second beginning-of-sequence token. The model trains on a start it never sees at inference time. Passadd_special_tokens=Falseon rendered text. - Missing end-of-turn token. If a hand-built string lacks it, the adapter never learns to stop. Generation then runs to the maximum length.
- Padding token. Some tokenizers define no pad token. Setting
tok.pad_token = tok.eos_tokenworks, but then padding positions must be masked out of the loss. The trainer's collator does this for its own batches. A hand-written collator must do it too. - Truncation. Cutting a long example at the maximum length can remove the assistant reply entirely. Such an example then has no trained tokens. Filter long examples out, as in the script above, instead of relying on truncation.
- Template mismatch at inference. Training with one template and prompting with another degrades quality in ways that look like a bad adapter. Use
apply_chat_template(..., add_generation_prompt=True)for both. - Train and validation leakage. Near-duplicate questions with different answers split across both sets inflate the validation score. Deduplicate before you split, as the script does.
How much data
For style, format, or narrow-task adaptation, a few hundred to a few thousand clean examples often suffice. Quality dominates quantity. A small set with consistent answers beats a large set with contradictory ones, because the adapter has few parameters and will average over conflicts. Read a random sample of at least fifty examples by eye before you train.
Exercise
You train an adapter on Qwen2.5-0.5B-Instruct using a hand-written prompt format such as "User: ... Assistant: ..." instead of the model's chat template. At inference you use apply_chat_template. Name two likely symptoms, and say how to fix the data.
Show answer
Likely symptoms are weaker answers than expected, because the adapter learned a layout the model is not prompted with, and replies that do not stop or that repeat the "User:" and "Assistant:" labels, because the end-of-turn token was never trained. To fix it, convert the data to the messages shape and render it with the tokenizer's own chat template for both training and inference. Then retrain the adapter.
Exercise
A training example has a 40-token prompt and a 10-token reply. With no masking, what fraction of the tokens carries loss, and what fraction with prompt masking? Ignore template tokens.
Show answer
Without masking, all 50 tokens carry loss, which is 100 percent, and 80 percent of that signal is spent on the prompt. With prompt masking, only the 10 reply tokens carry loss, which is 20 percent of the tokens, so every gradient step focuses on the answer.