Advanced about 6 h
The picture
01
Examples
prompt → ideal reply
02
Chat template
role tokens
03
Mask
train on replies only
04
Train
low LR, 1 to 3 epochs
05
Evaluate
held-out + regression
What SFT does
Show the model many examples of (prompt → ideal response) and train it with the usual next-token cross-entropy loss, but only on the response tokens. After pre-training, a model can continue text; SFT teaches it to behave like an assistant, or like your specialised assistant.
Data format
Use conversations in the model's chat format, one JSON object per line:
{"messages": [
{"role": "system", "content": "Extract invoice fields as JSON."},
{"role": "user", "content": "ACME Ltd Invoice #4471 ... total INR 12,400 due 2025-03-01"},
{"role": "assistant", "content": "{\"vendor\":\"ACME Ltd\",\"invoice_number\":\"4471\",\"total\":12400,\"currency\":\"INR\",\"due_date\":\"2025-03-01\"}"}
]}
Loss masking, by hand
Only the assistant's tokens should contribute to the loss. Labels of -100 are ignored by PyTorch's cross-entropy.
def encode(example, tok, max_len=2048):
msgs = example["messages"]
prompt_text = tok.apply_chat_template(msgs[:-1], tokenize=False, add_generation_prompt=True)
full_text = tok.apply_chat_template(msgs, tokenize=False)
p = tok(prompt_text, add_special_tokens=False)["input_ids"]
f = tok(full_text, add_special_tokens=False)["input_ids"][:max_len]
labels = ([-100] * len(p) + f[len(p):])[:max_len]
return {"input_ids": f, "labels": labels, "attention_mask": [1] * len(f)}
Libraries can do this for you, but understanding it prevents the classic bug of training the model to repeat the user's prompt.
A TRL run
import torch
from datasets import load_dataset
from transformers import AutoTokenizer, AutoModelForCausalLM
from trl import SFTTrainer, SFTConfig
name = "Qwen/Qwen2.5-1.5B" # a small base model for the exercise
tok = AutoTokenizer.from_pretrained(name)
model = AutoModelForCausalLM.from_pretrained(name, torch_dtype=torch.bfloat16)
ds = load_dataset("json", data_files={"train": "train.jsonl", "eval": "eval.jsonl"})
args = SFTConfig(
output_dir="out/sft",
num_train_epochs=2,
per_device_train_batch_size=4,
gradient_accumulation_steps=8, # effective batch 32
learning_rate=1e-5, # full fine-tuning: small
lr_scheduler_type="cosine",
warmup_ratio=0.03,
bf16=True,
logging_steps=10,
eval_strategy="steps", eval_steps=100,
save_strategy="steps", save_steps=100, save_total_limit=2,
max_length=2048,
)
trainer = SFTTrainer(model=model, args=args, train_dataset=ds["train"], eval_dataset=ds["eval"], processing_class=tok)
trainer.train()
trainer.save_model("out/sft/final")
Parameter names in these libraries change between releases (for example max_length versus max_seq_length), so check the docs for your installed version.
Reading the curves
- Train and eval loss both falling: good.
- Eval loss rising while train falls: you are memorising. Stop earlier, lower the learning rate, add data or regularise.
- Loss spikes: learning rate too high, or bad examples (check the batch at the spike).
Loss is a proxy. The real test is task accuracy on a held-out set, plus general-capability regression checks.
Practical guidance
- Learning rate: full fine-tuning around 1e-5 to 2e-5; LoRA tolerates 1e-4 to 3e-4.
- Epochs: 1 to 3 for most datasets. More is rarely better on small data.
- Packing several short examples per sequence improves throughput.
- Mix in general data (a few percent) if you see forgetting.
- Use the exact chat template at inference that you used in training.
Common mistakes
- Training on prompt tokens as well as responses.
- Different templates in training and serving.
- Judging by the loss curve alone.
Exercises
- Fine-tune a 0.5B to 1.5B model on 1,000 examples and report accuracy before and after on a held-out set.
- Deliberately train for 10 epochs and show what overfitting looks like in the curves and the outputs.
You are done when you can…
- Format a dataset into the model's chat template and mask the prompt tokens from the loss
- Run an SFT job and read its loss curves
- Choose a learning rate and epoch count that avoid overfitting a small dataset