AI Hints
Home›Fine-Tuning LLMs Tutorial›Your First LoRA Fine-Tune
Fine-Tuning LLMs · Lesson 49 of 120

TRL and SFTTrainer

Supervised fine-tuning.

⏱ 2 min read▶ Video at 1:17:59🎓 Free
Watch this lesson in the Fine-Tuning LLMs courseWatch on YouTube ↗Full Fine-Tuning LLMs course

Everything comes together now. A model, LoRA settings, and chat data. TRL gives us one trainer that connects them all. It's called the SFT trainer.

  • Model, LoRA, data
  • TRL connects them
  • The SFT trainer

What SFT means

SFT stands for supervised fine-tuning. Supervised means every example comes with the right answer. It's the first, and most common, kind of fine-tuning for language models. The SFT trainer is built on the normal Trainer, but it also knows about chat templates, completion only loss, and PEFT.

keyvalue
SFTsupervised fine-tuning
Supervisedevery example has the answer
SFTTrainerTrainer + chat + PEFT
Most commonthe first step for LLMs

sft.py

Here's s f t dot p y. We load the tokenizer and the model. The LoRA config uses rank sixteen, alpha thirty two, on all linear layers. SFT config holds the training settings. One epoch, a learning rate of two times ten to the minus four, and batches of eight. We log every eleven steps, and evaluate on the test set every twenty two. Finally, the SFT trainer gets the model, the settings, the data, the tokenizer, and the LoRA config. It adds the adapters for us.

sft.pypython
from transformers import AutoTokenizer, AutoModelForCausalLM
from peft import LoraConfig
from trl import SFTTrainer, SFTConfig
from chat import data

NAME = "HuggingFaceTB/SmolLM2-135M-Instruct"
tok = AutoTokenizer.from_pretrained(NAME)
model = AutoModelForCausalLM.from_pretrained(NAME)
lora = LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05,
                  target_modules="all-linear", task_type="CAUSAL_LM")
args = SFTConfig(output_dir="ticket-lora", num_train_epochs=1, learning_rate=2e-4,
                 per_device_train_batch_size=8, logging_steps=11,
                 eval_strategy="steps", eval_steps=22,
                 save_strategy="no", report_to="none")
trainer = SFTTrainer(model=model, args=args, train_dataset=data["train"],
                     eval_dataset=data["test"], processing_class=tok, peft_config=lora)

Summary

Let's recap. SFT means training on examples with the right answers. The SFT trainer handles chat data, and adds LoRA when we pass a peft config. And all our settings fit in one short file. Next, a closer look at SFT config.

Key takeaways
  • Supervised fine-tuning
  • SFTTrainer + peft_config
  • sft.py
Next up: SFTConfig — the training settings