Sub topic 2
Adding a LoRA Adapter with PEFT
This chapter assumes basic Python, PyTorch, transformers inference, and matrix multiplication. You should also know that a causal language model predicts the next token in a sequence.
Adding an adapter with PEFT
Parameter-Efficient Fine-Tuning (PEFT) trains a small set of new parameters while keeping the base model frozen. Low-Rank Adaptation (LoRA) adds two small matrices to selected linear layers:
\[ W' = W + \frac{\alpha}{r}BA \]
Here, r is the adapter rank, and alpha controls its scale. The target_modules list selects the layers that receive adapters.
from transformers import AutoModelForCausalLM
from peft import LoraConfig, get_peft_model
model = AutoModelForCausalLM.from_pretrained(
"Qwen/Qwen2.5-0.5B-Instruct"
)
config = LoraConfig(
r=16,
lora_alpha=32,
lora_dropout=0.05,
target_modules=["q_proj", "k_proj", "v_proj", "o_proj"],
task_type="CAUSAL_LM",
)
model = get_peft_model(model, config)
model.print_trainable_parameters()The printed count should show that only a small fraction of parameters is trainable. A higher rank can represent more task-specific behavior, but it uses more memory. Dropout randomly disables adapter paths during training and can reduce overfitting.
Preparing data and chat templates
A conversational dataset usually stores each example as messages with user and assistant roles. The tokenizer's chat template converts those messages into the exact token format expected by the model. Use the template associated with the base model rather than manually inventing role markers.
Training the adapter with SFTTrainer
Supervised fine-tuning (SFT) teaches the model to produce provided assistant responses. TRL's SFTTrainer can apply the chat template and attach the PEFT configuration.
from datasets import Dataset
from peft import LoraConfig
from trl import SFTConfig, SFTTrainer
data = Dataset.from_list([{
"messages": [
{"role": "user", "content": "Define LoRA."},
{"role": "assistant", "content": "LoRA trains small low-rank matrices beside frozen weights."},
]
}])
trainer = SFTTrainer(
model="Qwen/Qwen2.5-0.5B-Instruct",
train_dataset=data,
args=SFTConfig(
output_dir="adapter-out",
num_train_epochs=1,
per_device_train_batch_size=1,
learning_rate=2e-4,
),
peft_config=LoraConfig(r=16, lora_alpha=32, task_type="CAUSAL_LM"),
)
trainer.train()
trainer.save_model("adapter-out")Quantization basics for fine-tuning
Quantization stores weights with fewer bits. A 4-bit base model uses much less GPU memory, but its frozen weights are approximate. QLoRA combines a 4-bit base with higher-precision LoRA parameters. This reduces memory while keeping the trainable update expressive. In practice, QLoRA normally requires a CUDA-capable GPU and bitsandbytes.
Exercise
Why does LoRA reduce training storage compared with full fine-tuning?
Show answer
It freezes the original weights and saves only the small trainable adapter matrices.