Sub topic 8
Training the adapter with SFTTrainer
This chapter assumes you can run a Hugging Face transformers model, know what a LoRA adapter is, and have already seen how LoraConfig and get_peft_model work. It also assumes your data is in chat format. Here you will turn those pieces into a training run with TRL's SFTTrainer, read the logs, and fix the usual errors.
What SFTTrainer does
Supervised fine-tuning (SFT) trains a model on examples of the output you want. For each example, the model predicts the next token at every position, and the loss is cross-entropy against the real next token. SFTTrainer is a subclass of the transformers Trainer. It adds the steps that are specific to language-model SFT:
- It loads the model and tokenizer from a model ID if you pass a string.
- It applies the tokenizer's chat template to
messagesdata and tokenizes the result. - It wraps the model with a LoRA adapter when you pass
peft_config. - It batches and pads sequences, and can pack several short examples into one sequence.
Because it extends Trainer, everything in TrainingArguments still works. SFTConfig extends TrainingArguments with SFT options such as max_length, packing and dataset_text_field.
A complete training script
The script below builds a small synthetic dataset so it runs without any download beyond the model. Replace the dataset with your own data for real work.
from datasets import Dataset
from peft import LoraConfig
from trl import SFTConfig, SFTTrainer
pairs = [(f"Add {i} and {i + 1}.", f"The sum is {2 * i + 1}.") for i in range(60)]
rows = [
{"messages": [
{"role": "user", "content": q},
{"role": "assistant", "content": a},
]}
for q, a in pairs
]
splits = Dataset.from_list(rows).train_test_split(test_size=0.1, seed=42)
config = SFTConfig(
output_dir="lora-out",
num_train_epochs=2,
per_device_train_batch_size=4,
gradient_accumulation_steps=4,
learning_rate=2e-4,
lr_scheduler_type="cosine",
warmup_ratio=0.05,
weight_decay=0.0,
logging_steps=1,
eval_strategy="steps",
eval_steps=2,
save_strategy="no",
max_length=512,
report_to="none",
)
trainer = SFTTrainer(
model="Qwen/Qwen2.5-0.5B-Instruct",
train_dataset=splits["train"],
eval_dataset=splits["test"],
args=config,
peft_config=LoraConfig(
r=16,
lora_alpha=32,
lora_dropout=0.05,
target_modules="all-linear",
task_type="CAUSAL_LM",
),
)
trainer.train()
trainer.save_model("lora-out/adapter")On a GPU that supports bfloat16, add bf16=True to SFTConfig. Without it, training runs in float32, which is slower and uses more memory.
The settings that matter
Batch size and gradient accumulation
Memory use depends on the per-device batch size and the sequence length. Optimization quality depends on the effective batch size:
effective batch = per_device_train_batch_size × gradient_accumulation_steps × number_of_devicesIn the script above this is 4 × 4 × 1 = 16. The training split holds 54 examples, so one epoch is ceil(54 / 16) = 4 optimizer steps, and two epochs give 8 steps. Gradient accumulation lets you reach a stable effective batch on a small GPU by running several small forward and backward passes before each optimizer step.
Learning rate
LoRA tolerates and usually needs a much higher learning rate than full fine-tuning. Values around 1e-4 to 3e-4 are common starting points for adapters. Full fine-tuning typically uses 1e-5 or lower. A cosine or linear schedule with a short warmup (a few percent of steps) avoids early instability.
Sequence length
max_length truncates each tokenized example. Truncation can cut off the assistant's answer, so the model never learns the end of the response. Measure your token lengths first and set max_length above, for example, the 95th percentile. In older TRL releases this option is called max_seq_length, so check the version you installed.
Packing
With packing=True, TRL concatenates short examples into full-length sequences. This removes padding waste and speeds up training on datasets of short examples. Packed examples can attend to each other unless you use a padding-free or attention-masking setup that your TRL and attention backend support, so leave packing off until the basic run works.
Which tokens contribute to the loss
By default the loss is computed over all tokens, including the user prompt. Often you only want the model to learn the assistant's reply. Recent TRL versions offer options for this, such as assistant_only_loss=True for conversational data and completion_only_loss for prompt/completion data. assistant_only_loss requires a chat template that marks assistant spans with generation tags, and many stock templates do not have them. Check the documentation for your installed version before relying on either option.
Reading the training logs
With logging_steps=1 you get a line per step with loss and learning_rate, and an eval_loss line every eval_steps. Use them like this:
| Pattern | Likely meaning | What to try |
|---|---|---|
| Train loss falls, eval loss falls | Healthy run | Continue, then evaluate on real tasks |
| Train loss falls, eval loss rises | Overfitting | Fewer epochs, lower rank, more dropout, more data |
| Loss stays flat | Learning rate too low, wrong target modules, or no trainable parameters | Check `print_trainable_parameters()`, raise the learning rate |
| Loss becomes `nan` or jumps | Learning rate too high or fp16 overflow | Lower the learning rate, use bf16, add gradient clipping |
| Loss drops to near zero within a few steps | Duplicate or leaked examples, or a trivial dataset | Deduplicate, check train/eval overlap |
A low loss does not mean a useful model. It measures next-token prediction on your data, not whether answers are correct. The next chapters cover evaluation against the base model.
Memory levers
If you hit a CUDA out-of-memory error, change one setting at a time, roughly in this order:
- Lower
per_device_train_batch_sizeand raisegradient_accumulation_stepsby the same factor. - Lower
max_length. - Set
gradient_checkpointing=TrueinSFTConfig. This recomputes activations during the backward pass, trading compute for memory. - Use
bf16=Trueif the GPU supports it. - Load the base model in 4-bit (QLoRA, covered in a later chapter).
The base weights are frozen, so they need no gradients or optimizer state. Only A and B carry optimizer state. Most of the remaining memory goes to activations, which is why batch size, sequence length and checkpointing have the largest effect.
What gets saved
When the model is a PEFT model, trainer.save_model("lora-out/adapter") writes only the adapter: adapter_config.json and adapter_model.safetensors. These files are small, often tens of megabytes. The base model weights are not copied. The adapter config records the base model name, so you can load the adapter onto that same base later.
Common errors
ValueErroror a missing-column error about the dataset format.SFTTrainerexpects amessagescolumn, aprompt/completionpair, or a text column. Check column names withds.column_names.TypeError: unexpected keyword argument 'max_seq_length'(or the reverse). The option was renamed between TRL versions. Match the name to your installed version.element 0 of tensors does not require grad. This occurs with gradient checkpointing when the inputs to the checkpointed blocks have no gradient path. Make sure the model is a PEFT model and that you are on a recent TRL and PEFT. Callingmodel.enable_input_require_grads()is the usual fix when you build the model yourself.- Model repeats the prompt or never stops. The end-of-turn token is missing from the training text, or the chat template differs between training and inference. Print one formatted example and check that it ends the way inference expects.
- Training is slow on a short dataset. Padding to a long
max_lengthwastes compute. Lower it, or try packing.
Exercise
You train with perdevicetrainbatchsize=2, gradientaccumulationsteps=8 on 2 GPUs, with 640 training examples and 3 epochs. What is the effective batch size and how many optimizer steps does the run take?
Show answer
The effective batch size is 2 × 8 × 2 = 32. One epoch is 640 / 32 = 20 optimizer steps, so three epochs take 60 steps.
Exercise
Train loss keeps falling over three epochs, but eval loss reaches its minimum after epoch one and then rises. Name two changes you could make and what the symptom tells you.
Show answer
The model is overfitting to the training set. Reduce the number of epochs to about one, or lower the rank, raise lora_dropout, or add more varied training data. Keeping the checkpoint from the eval-loss minimum also works.
Exercise
After training, trainer.save_model writes a directory of only a few tens of megabytes for a multi-gigabyte base model. Is something wrong?
Show answer
No. With a PEFT model, only the adapter weights and adapter_config.json are saved. The base model is referenced by name and must be loaded separately, or merged with the adapter in a later step.