Sub topic 12
Fine-tuning with LoRA
This chapter assumes you finished the Trainer chapters. You should have checkpoint, tokenizer, train_ds, val_ds, test_ds and compute_metrics defined as before, and you should know what a weight matrix and a gradient are. LoRA changes which parameters get trained. The data pipeline, the metrics and the Trainer stay the same.
Why full fine-tuning can be a problem
Full fine-tuning updates every weight in the encoder. For DistilBERT, with about 67 million parameters, that is fine on one GPU. The cost grows with model size, and it shows up in three places:
- Memory. AdamW keeps two extra values per trainable parameter, plus the gradient. Training memory is several times the size of the weights.
- Storage. Each task produces a full copy of the model. Ten tasks on a 400 MB model means 4 GB of checkpoints.
- Serving. Switching between tasks means loading a whole new model.
Parameter-efficient fine-tuning (PEFT) freezes the pretrained weights and trains a small number of new ones. LoRA (Low-Rank Adaptation) is the most widely used PEFT method.
How LoRA works
Take a frozen weight matrix W with shape d_out × d_in. Full fine-tuning learns a change ΔW of the same shape. LoRA assumes that ΔW has low rank and writes it as the product of two thin matrices:
Ahas shaper × d_in.Bhas shaped_out × r.- The layer output becomes
W x + (alpha / r) · B A x.
r is the rank, typically 4 to 64. A starts with small random values and B starts at zero. At step 0 the adapter adds nothing, so the model behaves exactly like the pretrained one.
A square 768 × 768 projection has 589,824 weights. A rank-8 adapter on it has 8 × 768 + 768 × 8 = 12,288 weights, about 2% of the original.
The settings that matter
| Setting | Meaning | Typical value |
|---|---|---|
| `r` | Rank of the update. Higher means more capacity and more parameters. | 8 to 16 for classification |
| `lora_alpha` | Scaling numerator. The update is multiplied by `lora_alpha / r`. | `r` or `2 * r` |
| `lora_dropout` | Dropout applied to the adapter input. | 0.05 to 0.1 |
| `target_modules` | Names of the layers that receive adapters. | Attention query and value projections |
| `modules_to_save` | Layers trained in full and saved with the adapter. | The classification head |
Because the scale is lora_alpha / r, changing r without changing lora_alpha also changes the effective step size. Keeping the ratio fixed (here 16 / 8 = 2) makes rank comparisons fairer.
Wrapping DistilBERT with LoRA
target_modules must match layer names in the model. DistilBERT calls its attention projections q_lin, k_lin, v_lin and out_lin. BERT and RoBERTa use query and value. You can list the names with model.named_modules().
The classification head matters here. Its weights are newly initialized, so they must be trained. TaskType.SEQ_CLS makes PEFT train and save modules named classifier and score. DistilBERT's head also has a pre_classifier layer. PEFT does not add it for you, so it would stay frozen at its random initial values. List both layers explicitly.
from peft import LoraConfig, TaskType, get_peft_model
from transformers import AutoModelForSequenceClassification
checkpoint = "distilbert-base-uncased"
id2label = {0: "NEGATIVE", 1: "POSITIVE"}
label2id = {v: k for k, v in id2label.items()}
base = AutoModelForSequenceClassification.from_pretrained(
checkpoint, num_labels=2, id2label=id2label, label2id=label2id
)
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, lora_config)
model.print_trainable_parameters()The printout reports roughly 0.74 million trainable parameters, about 1% of the total. Of those, 147,456 are LoRA weights (6 layers × 2 projections × 12,288). The rest is the head, and pre_classifier alone is about 590,000.
Training with the same Trainer
The wrapped model is a normal PyTorch module, so the Trainer, the data collator and compute_metrics work unchanged. One setting does change: the learning rate. Freshly initialized low-rank matrices need larger steps than a pretrained encoder that is being nudged. Values from 1e-4 to 3e-4 are common, roughly ten times the 2e-5 used for full fine-tuning.
from transformers import DataCollatorWithPadding, Trainer, TrainingArguments
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=args,
train_dataset=train_ds,
eval_dataset=val_ds,
data_collator=DataCollatorWithPadding(tokenizer),
compute_metrics=compute_metrics,
)
trainer.train()
print(trainer.evaluate(test_ds))Compare the test F1 with your full fine-tuning run. On a small encoder and an easy task like IMDB, the gap is usually small, often within a point. It tends to grow when the task differs a lot from pretraining or when r is too low.
Saving, loading and merging
Calling trainer.save_model() on a PEFT model writes only the adapter and the saved head modules. The folder is a few megabytes. It records the name of the base checkpoint, so loading it downloads or reads the base model and applies the adapter on top.
You have two ways to serve the result:
- Keep the adapter separate. Load the base once and attach different adapters per task. This suits many tasks on one base model.
- Merge into the base. The merged weights are
W + (alpha / r) · B A. The result is an ordinary Transformers model with no extra latency from the adapter path, and it works with any tool that loads standard checkpoints.
from peft import AutoPeftModelForSequenceClassification
from transformers import pipeline
trainer.save_model("imdb-distilbert-lora")
tuned = AutoPeftModelForSequenceClassification.from_pretrained("imdb-distilbert-lora")
merged = tuned.merge_and_unload()
merged.config.id2label = id2label
merged.config.label2id = label2id
merged.save_pretrained("imdb-distilbert-merged")
tokenizer.save_pretrained("imdb-distilbert-merged")
classifier = pipeline("text-classification", model="imdb-distilbert-merged")
print(classifier(["A warm, funny film with a great cast.", "Two hours I will never get back."]))The label names are set on the config after loading because the adapter folder does not store them. Without that step the pipeline would report LABEL_0 and LABEL_1. Save the tokenizer next to the model so that the merged folder works on its own.
Choosing between LoRA and full fine-tuning
| Situation | Better choice |
|---|---|
| Small encoder, one task, plenty of GPU memory | Full fine-tuning is simple and slightly stronger |
| Large model that barely fits in memory | LoRA |
| Many tasks or customers sharing one base model | LoRA, with one small adapter each |
| Target data far from the pretraining domain | Full fine-tuning, or LoRA with a higher `r` and more target modules |
| Must ship a single standard checkpoint | Either, with LoRA merged afterward |
For a model the size of DistilBERT, LoRA is mostly a way to learn the workflow. The payoff is larger with models of hundreds of millions of parameters or more.
Common errors
- The head stays random. If
modules_to_savedoes not cover every new head layer, the model trains but scores badly. Check thatprint_trainable_parameters()includes the head. - No adapters attached. A wrong
target_modulesname raises an error such as "Target modules not found". Print the module names and match them exactly. - Learning rate copied from full fine-tuning.
2e-5often leaves LoRA under-trained. If the validation loss barely moves, raise the rate before raisingr. - Loading the adapter on a different base. The adapter only makes sense with the exact base checkpoint it was trained on.
- Merging, then training more. After
merge_and_unload()the adapter is gone. Keep the unmerged adapter folder if you may continue training.
Exercise
A teammate trains DistilBERT with LoRA using target_modules=["q_lin", "v_lin"] and no modules_to_save, using TaskType.SEQ_CLS. Validation accuracy is lower than with full fine-tuning. Which layer is likely still at its random initial values, and how do you fix it? Also compute how many LoRA weights one 768 × 768 projection gets at r=8.
Show answer
The pre_classifier layer. PEFT's sequence-classification task type trains and saves classifier automatically but not DistilBERT's pre_classifier, so it stays frozen at random values. Fix it by passing modules_to_save=["pre_classifier", "classifier"] to LoraConfig. One 768 × 768 projection at rank 8 gets 8 × 768 (matrix A) plus 768 × 8 (matrix B), which is 12,288 weights.
Exercise
You change r from 8 to 32 and keep lora_alpha=16. What happens to the scaling factor applied to the adapter output, and what would you set lora_alpha to if you want the scaling to stay at 2?
Show answer
The scaling factor lora_alpha / r drops from 16 / 8 = 2 to 16 / 32 = 0.5, so each update has a quarter of its earlier effect. To keep the scale at 2, set lora_alpha=64.