Sub topic 8
Training the adapter with SFTTrainer
This chapter assumes you can run a Hugging Face transformers model for inference, know what a LoRA adapter is, and have seen how LoraConfig and get_peft_model work. You also need a dataset in chat format, as covered in the previous chapter. Here you train the adapter with TRL's SFTTrainer.
What SFTTrainer does for you
Supervised fine-tuning (SFT) trains the model to reproduce the assistant replies in your examples. SFTTrainer is a wrapper around the transformers Trainer. It handles the steps that are easy to get wrong by hand:
- It loads the model and tokenizer from a model id.
- It applies the chat template to a
messagescolumn. - It tokenizes and batches the text.
- It wraps the model with the adapter described by
peft_config. - It runs the training loop and logs the loss.
Because you pass peft_config, you do not call get_peft_model yourself. The trainer does it, and only the adapter weights receive gradients.
A minimal training run
The example below uses one training example so it runs quickly. It only shows the mechanics. A real run needs hundreds or thousands of examples.
from datasets import Dataset
from peft import LoraConfig
from trl import SFTConfig, SFTTrainer
train_ds = Dataset.from_list([
{"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."},
]},
])
trainer = SFTTrainer(
model="Qwen/Qwen2.5-0.5B-Instruct",
train_dataset=train_ds,
args=SFTConfig(
output_dir="lora-out",
num_train_epochs=1,
per_device_train_batch_size=1,
learning_rate=2e-4,
logging_steps=1,
),
peft_config=LoraConfig(r=16, lora_alpha=32, task_type="CAUSAL_LM"),
)
trainer.train()
trainer.save_model("lora-out/adapter")SFTConfig extends TrainingArguments, so every familiar option still works. The ones that matter most for LoRA are in the table below.
| Setting | Typical starting value | Why |
|---|---|---|
| `learning_rate` | `1e-4` to `2e-4` | Adapters tolerate and need a higher rate than full fine-tuning, which often uses `1e-5` or lower. |
| `num_train_epochs` | 1 to 3 | More epochs on a small dataset invites overfitting. |
| `per_device_train_batch_size` | As large as memory allows | Combine with `gradient_accumulation_steps` for a larger effective batch. |
| `gradient_accumulation_steps` | 4 to 16 | Effective batch size is the per-device batch size times this value times the number of GPUs. |
| `logging_steps` | 1 to 10 | Frequent logs help you spot a bad loss curve early. |
Reading the loss
The trainer logs the training loss, which is the average cross-entropy of the next-token predictions. Check three things:
- The loss should fall in the first steps, then flatten.
- A starting loss near zero usually means the data is trivial or the labels are wrong.
- A loss that falls to almost zero over several epochs on a small set signals memorization.
If you also pass eval_dataset and set an evaluation strategy in SFTConfig, the trainer logs an evaluation loss. A widening gap between the two losses is the first sign of overfitting.
Common errors
- Loss is
nanor does not move. The learning rate is probably too high. Lower it by a factor of 2 to 5. Also check that half-precision settings match your hardware. - Out-of-memory error. Lower the per-device batch size and raise gradient accumulation to keep the effective batch size. Shortening the maximum sequence length also helps.
- Output ignores your format at inference. The chat template at inference differs from the one used in training. Build prompts with the same tokenizer's
apply_chat_template. - You saved the wrong thing.
save_modelon a PEFT-wrapped model writes only the adapter files, which are small. That is expected. Loading them needs the same base model.
Exercise
You train for 3 epochs on 200 examples. Training loss reaches 0.05, but evaluation loss rose after epoch 1. What is happening, and what are two changes you could make?
Show answer
The adapter is overfitting: it memorizes the training examples instead of generalizing. Reduce the number of epochs (stopping near epoch 1) and lower the learning rate or add more varied training data. Raising lora_dropout or lowering the rank r can also help.