Sub topic 12
Fine-tuning with LoRA
This chapter assumes you know Python, PyTorch tensors, training and validation splits, and the Hugging Face Trainer API. It also assumes you have already seen how to tokenize text and attach a classification head to a pretrained encoder.
Why use LoRA?
Full fine-tuning updates every parameter in the pretrained transformer. This can work well, but it needs substantial memory. It also creates a complete copy of the model for every task.
LoRA, or Low-Rank Adaptation, freezes the original model and adds small trainable matrices to selected layers. During training, only these adapters and usually the task-specific classification head are updated.
A transformer layer contains weight matrices that transform hidden states. LoRA learns a small update to one of these matrices:
W' = W + \Delta WInstead of learning every value in the full update matrix \(\Delta W\), LoRA represents it as:
\Delta W = B AThe matrices \(A\) and \(B\) have a small rank, such as 8. This greatly reduces the number of trainable parameters.
| Method | Base model parameters | Task-specific storage | Typical advantage |
|---|---|---|---|
| Full fine-tuning | Trainable | Full model copy | Maximum flexibility |
| LoRA | Frozen | Small adapter and head | Lower memory and faster updates |
| Prompt-based methods | Frozen | Learned prompt values | Very small update, sometimes less reliable |
LoRA is useful when the base model is large, GPU memory is limited, or you need separate adapters for many tasks. It may be less suitable when the task requires broad changes to the model's behavior.
Adding LoRA adapters
The peft library, which means Parameter-Efficient Fine-Tuning, integrates LoRA models with the Transformers Trainer.
For DistilBERT, the attention module names include q_lin for the query projection and v_lin for the value projection. We can place adapters in those projections and keep the classification head trainable.
from transformers import AutoModelForSequenceClassification
from peft import LoraConfig, TaskType, get_peft_model
checkpoint = "distilbert-base-uncased"
base_model = AutoModelForSequenceClassification.from_pretrained(
checkpoint,
num_labels=2,
id2label={0: "NEGATIVE", 1: "POSITIVE"},
label2id={"NEGATIVE": 0, "POSITIVE": 1},
)
lora_config = LoraConfig(
task_type=TaskType.SEQ_CLS,
r=8,
lora_alpha=16,
lora_dropout=0.1,
target_modules=["q_lin", "v_lin"],
modules_to_save=["pre_classifier", "classifier"],
)
model = get_peft_model(base_model, lora_config)
model.print_trainable_parameters()The r value is the adapter rank. A larger rank gives LoRA more capacity but increases memory and computation. lora_alpha scales the adapter update. lora_dropout randomly drops part of the adapter input during training, which can reduce overfitting.
target_modules controls where adapters are inserted. Different model families use different names. For example, another architecture might call its projections q_proj and v_proj. Check the model's module names before choosing this setting.
modules_to_save keeps the classification layers trainable and saves them with the adapter. Without this setting, the new head may not learn the task correctly or may not be included in the reusable adapter package.
Training and saving the adapter
The PEFT-wrapped model can be passed to the same Trainer used for full fine-tuning. Keep the validation set and evaluation metrics unchanged so that the two approaches can be compared fairly.
from transformers import Trainer, TrainingArguments
training_args = TrainingArguments(
output_dir="imdb-distilbert-lora",
learning_rate=2e-4,
per_device_train_batch_size=16,
per_device_eval_batch_size=32,
num_train_epochs=3,
weight_decay=0.01,
eval_strategy="epoch",
save_strategy="epoch",
load_best_model_at_end=True,
metric_for_best_model="f1",
)
trainer = Trainer(
model=model,
args=training_args,
train_dataset=train_ds,
eval_dataset=val_ds,
data_collator=data_collator,
compute_metrics=compute_metrics,
)
trainer.train()
trainer.save_model("imdb-distilbert-lora")LoRA often uses a higher learning rate than full fine-tuning because the adapter parameters start from a small initialization while the base model remains fixed. This is a starting point, not a rule. Use validation results to compare learning rates and ranks.
Common errors and decisions
- Wrong module names: Inspect the model architecture before setting
target_modules. - Frozen classification head: Include the task head in
modules_to_save, or verify its parameters are trainable. - Rank too high: A high rank increases cost and can overfit small datasets.
- Comparing unfair runs: Keep data splits, evaluation metrics, and checkpoint-selection rules the same.
- Forgetting the base model: An adapter usually cannot run without its compatible base model.
Exercise
Why does LoRA reduce training memory, and which parameters should usually remain trainable for a new classification task?
Show answer
LoRA freezes the large base model and trains small low-rank adapter matrices instead. The adapters and the new classification head should usually remain trainable.