LoRA with Hugging Face PEFT
The previous lesson wrote LoRA by hand: two thin matrices per adapted layer, their gradients, and the merge. In practice nobody writes that for a transformer with dozens of layers. Hugging Face PEFT (Parameter-Efficient Fine-Tuning) wraps any Transformers model: you name the layers to adapt, it replaces each with a LoRA layer, freezes everything else, and saves only the adapter. This lesson fine-tunes a small pretrained BERT for movie-review sentiment with PEFT, compares it with full fine-tuning on the same data, saves the adapter and merges it back.
What PEFT does to a model
get_peft_model(model, LoraConfig(...)) walks the model, and for every module whose name matches target_modules it swaps the nn.Linear for a lora.Linear that holds the original layer (base_layer, frozen) plus lora_A and lora_B. Every other parameter gets requires_grad = False, except the modules listed in modules_to_save, which are copied and trained in full. For task_type="SEQ_CLS" PEFT adds the classification head there automatically, because a new task's head is new and must learn.
The LoraConfig fields map one to one onto the formula :
| Field | Meaning | Typical value |
|---|---|---|
r |
rank of | 4 to 16 |
lora_alpha |
; the update is scaled by | or |
target_modules |
names of the linear layers to adapt | ["query", "value"] in BERT, ["q_proj", "v_proj"] in Llama, or "all-linear" |
lora_dropout |
dropout on the input of the side path | 0 to 0.1 |
task_type |
SEQ_CLS, CAUSAL_LM, TOKEN_CLS, ... (sets modules_to_save and the forward signature) |
|
modules_to_save |
extra modules trained in full and saved with the adapter | the head |
The model is google/bert_uncased_L-2_H-128_A-2, a BERT with 2 layers, hidden size 128 and 2 attention heads (4.4 million parameters). It is tiny by today's standards, which is what lets every run here finish in seconds on a CPU; the code is the same for a 7-billion-parameter model.
Wrapping the model
import torch
from transformers import AutoModelForSequenceClassification
from transformers.utils import logging
from peft import LoraConfig, get_peft_model
logging.set_verbosity_error() # hide the "classifier newly initialised" load report
torch.manual_seed(0)
base = AutoModelForSequenceClassification.from_pretrained("google/bert_uncased_L-2_H-128_A-2", num_labels=2)
print("before:", base.bert.encoder.layer[0].attention.self.query)
config = LoraConfig(task_type="SEQ_CLS", r=8, lora_alpha=16, lora_dropout=0.0, target_modules=["query", "value"])
model = get_peft_model(base, config)
model.print_trainable_parameters()
q = model.base_model.model.bert.encoder.layer[0].attention.self.query
print("after: ", type(q).__module__ + "." + type(q).__name__, "| base:", q.base_layer, "| A:", q.lora_A["default"], "| B:", q.lora_B["default"])
print("B starts at zero:", bool((q.lora_B["default"].weight == 0).all()))
for n, p in model.named_parameters():
if p.requires_grad:
print(" ", n.replace("base_model.model.", ""), tuple(p.shape))before: Linear(in_features=128, out_features=128, bias=True)
trainable params: 8,450 || all params: 4,394,628 || trainable%: 0.1923
after: peft.tuners.lora.layer.Linear | base: Linear(in_features=128, out_features=128, bias=True) | A: Linear(in_features=128, out_features=8, bias=False) | B: Linear(in_features=8, out_features=128, bias=False)
B starts at zero: True
bert.encoder.layer.0.attention.self.query.lora_A.default.weight (8, 128)
bert.encoder.layer.0.attention.self.query.lora_B.default.weight (128, 8)
bert.encoder.layer.0.attention.self.value.lora_A.default.weight (8, 128)
bert.encoder.layer.0.attention.self.value.lora_B.default.weight (128, 8)
bert.encoder.layer.1.attention.self.query.lora_A.default.weight (8, 128)
bert.encoder.layer.1.attention.self.query.lora_B.default.weight (128, 8)
bert.encoder.layer.1.attention.self.value.lora_A.default.weight (8, 128)
bert.encoder.layer.1.attention.self.value.lora_B.default.weight (128, 8)
classifier.modules_to_save.default.weight (2, 128)
classifier.modules_to_save.default.bias (2,)
The query projection was a plain Linear(128, 128); after wrapping it is PEFT's LoRA Linear that keeps the original as base_layer and adds lora_A (128 to 8) and lora_B (8 to 128, all zeros). Only 8,450 of 4.39 million parameters train, 0.19 %: four adapted layers (query and value in each of the 2 encoder layers) with each, plus the 258 numbers of the new 2-class head (), which PEFT put in modules_to_save because the task type is SEQ_CLS.
Training: LoRA against full fine-tuning
The data is the rotten_tomatoes set of the sentence-embeddings lesson: one-sentence movie reviews labelled positive or negative. To stay fast, a fixed random 2,000 training sentences and 500 test sentences, cut or padded to 48 word pieces. Every run trains for 3 epochs with AdamW, batches of 32 in the same shuffled order, and is scored once on the 500 test sentences. The learning rates follow the usual rule: about for LoRA, for full fine-tuning of this small model (for large models, to ).
The first run trains LoRA on the query and value projections, then saves the adapter and merges it:
import os, tempfile, warnings
import torch
from datasets import load_dataset
from transformers import AutoTokenizer, AutoModelForSequenceClassification
from transformers.utils import logging
from peft import LoraConfig, get_peft_model
logging.set_verbosity_error()
warnings.filterwarnings("ignore", message="Could not find a config file") # offline check of the base model's files
name = "google/bert_uncased_L-2_H-128_A-2"
ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
train = ds["train"].shuffle(seed=0).select(range(2000))
test = ds["test"].shuffle(seed=0).select(range(500))
tok = AutoTokenizer.from_pretrained(name)
enc = lambda d: tok(list(d["text"]), padding="max_length", truncation=True, max_length=48, return_tensors="pt")
X_tr, X_te = enc(train), enc(test)
y_tr, y_te = torch.tensor(train["label"]), torch.tensor(test["label"])
def fit_and_score(model, lr, epochs=3):
opt = torch.optim.AdamW([p for p in model.parameters() if p.requires_grad], lr=lr)
g = torch.Generator().manual_seed(0)
for _ in range(epochs):
model.train()
for idx in torch.randperm(len(y_tr), generator=g).split(32):
out = model(input_ids=X_tr["input_ids"][idx], attention_mask=X_tr["attention_mask"][idx], labels=y_tr[idx])
opt.zero_grad(); out.loss.backward(); opt.step()
model.eval()
with torch.no_grad():
logits = model(input_ids=X_te["input_ids"], attention_mask=X_te["attention_mask"]).logits
return (logits.argmax(1) == y_te).float().mean().item(), logits
torch.manual_seed(0)
model = AutoModelForSequenceClassification.from_pretrained(name, num_labels=2)
model = get_peft_model(model, LoraConfig(task_type="SEQ_CLS", r=8, lora_alpha=16, target_modules=["query", "value"]))
acc, logits = fit_and_score(model, lr=1e-3)
print(f"LoRA r=8 on query+value: test accuracy {acc:.3f} (500 sentences)")
with tempfile.TemporaryDirectory() as d: # what gets saved: the adapter only
model.save_pretrained(d)
files = sorted(os.listdir(d))
size = sum(os.path.getsize(os.path.join(d, f)) for f in files)
print("saved:", files, f"total {size / 1024:.0f} KiB")
print(f"the full model in float32 would be {sum(p.numel() for p in model.parameters()) * 4 / 2**20:.1f} MiB")
merged = model.merge_and_unload() # W0 + (alpha/r) B A, LoRA layers removed
with torch.no_grad():
m_logits = merged(input_ids=X_te["input_ids"], attention_mask=X_te["attention_mask"]).logits
print("merged model:", type(merged).__name__, "| same predictions:", bool(torch.equal(m_logits.argmax(1), logits.argmax(1))),
"| max logit difference below 1e-5:", bool((m_logits - logits).abs().max() < 1e-5))LoRA r=8 on query+value: test accuracy 0.704 (500 sentences)
saved: ['README.md', 'adapter_config.json', 'adapter_model.safetensors'] total 40 KiB
the full model in float32 would be 16.8 MiB
merged model: BertForSequenceClassification | same predictions: True | max logit difference below 1e-5: True
LoRA reaches 0.704 on the 500 test sentences. The saved directory holds the adapter weights, its config and a model card, 40 KiB in all, against 16.8 MiB for the whole model in float32: the ratio that makes "one base, many adapters" practical. After merge_and_unload() the result is a plain BertForSequenceClassification again, with the same predictions on every test sentence and logits equal up to float32 rounding.
The second run uses the same data and loop for LoRA on every linear layer of the encoder (query, key, value and the dense layers of attention output and feed-forward) and for full fine-tuning:
import torch
from datasets import load_dataset
from transformers import AutoTokenizer, AutoModelForSequenceClassification
from transformers.utils import logging
from peft import LoraConfig, get_peft_model
logging.set_verbosity_error()
name = "google/bert_uncased_L-2_H-128_A-2"
ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
train = ds["train"].shuffle(seed=0).select(range(2000))
test = ds["test"].shuffle(seed=0).select(range(500))
tok = AutoTokenizer.from_pretrained(name)
enc = lambda d: tok(list(d["text"]), padding="max_length", truncation=True, max_length=48, return_tensors="pt")
X_tr, X_te = enc(train), enc(test)
y_tr, y_te = torch.tensor(train["label"]), torch.tensor(test["label"])
def fit_and_score(model, lr, epochs=3):
opt = torch.optim.AdamW([p for p in model.parameters() if p.requires_grad], lr=lr)
g = torch.Generator().manual_seed(0)
for _ in range(epochs):
model.train()
for idx in torch.randperm(len(y_tr), generator=g).split(32):
out = model(input_ids=X_tr["input_ids"][idx], attention_mask=X_tr["attention_mask"][idx], labels=y_tr[idx])
opt.zero_grad(); out.loss.backward(); opt.step()
model.eval()
with torch.no_grad():
logits = model(input_ids=X_te["input_ids"], attention_mask=X_te["attention_mask"]).logits
return (logits.argmax(1) == y_te).float().mean().item()
for label, targets, lr in [("LoRA r=8, all linear", ["query", "key", "value", "dense"], 1e-3),
("full fine-tuning", None, 1e-4)]:
torch.manual_seed(0)
model = AutoModelForSequenceClassification.from_pretrained(name, num_labels=2)
if targets:
model = get_peft_model(model, LoraConfig(task_type="SEQ_CLS", r=8, lora_alpha=16, target_modules=targets))
acc = fit_and_score(model, lr)
n = sum(p.numel() for p in model.parameters() if p.requires_grad)
print(f"{label:22s} trainable {n:>9,} test accuracy {acc:.3f}")LoRA r=8, all linear trainable 39,170 test accuracy 0.724
full fine-tuning trainable 4,386,178 test accuracy 0.742
| Method (same data, 3 epochs) | Trainable parameters | Test accuracy (500 sentences) |
|---|---|---|
| new head only, encoder frozen (partial fine-tuning, lr ) | 258 | 0.574 |
| LoRA r = 8, query + value | 8,450 | 0.704 |
| LoRA r = 8, all linear layers | 39,170 | 0.724 |
| full fine-tuning | 4,386,178 | 0.742 |
A head on the frozen encoder reaches only 0.574; LoRA on two matrices per block lifts that to 0.704 with 8,192 more trainable numbers. Adapting every linear layer instead of two per block gains 0.020 (10 sentences) for 4.6 times more adapter parameters, and full fine-tuning is another 0.018 ahead. With a model this small, full fine-tuning is cheap, so the gap is the price of LoRA you would not pay here. The point of the comparison is the ratio: 39,170 trainable numbers got within 0.018 of 4.4 million. At 7 billion parameters that ratio decides whether training fits on one GPU at all (PEFT overview). One seed and 500 test sentences: the standard error of an accuracy near 0.72 is about 0.02, so of the three trained methods only the two ends (0.704 and 0.742) are clearly apart.
The same API for a causal language model
For GPT-style models the task type is CAUSAL_LM and the target names follow the architecture. GPT-2 stores its attention projections as one fused Conv1D called c_attn, whose weight is laid out transposed (inputs first), which is what fan_in_fan_out=True tells PEFT. The model sshleifer/tiny-gpt2 has the GPT-2 shape with random, tiny weights (2 layers, width 2), so it is good for checking the wiring, not for generating text:
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
from transformers.utils import logging
from peft import LoraConfig, get_peft_model
logging.set_verbosity_error()
torch.manual_seed(0)
tok = AutoTokenizer.from_pretrained("sshleifer/tiny-gpt2")
base = AutoModelForCausalLM.from_pretrained("sshleifer/tiny-gpt2")
print("layers:", base.config.n_layer, "| width:", base.config.n_embd, "| attention projection:", base.transformer.h[0].attn.c_attn)
batch = tok(["the cat sat on the mat"], return_tensors="pt")
with torch.no_grad():
before = base(**batch).logits
config = LoraConfig(task_type="CAUSAL_LM", r=4, lora_alpha=8, target_modules=["c_attn"], fan_in_fan_out=True)
model = get_peft_model(base, config)
model.print_trainable_parameters()
with torch.no_grad():
after = model(**batch).logits
print("logits shape:", tuple(after.shape), "| unchanged at initialisation:", torch.equal(after, before))layers: 2 | width: 2 | attention projection: Conv1D(nf=6, nx=2)
trainable params: 64 || all params: 102,778 || trainable%: 0.0623
logits shape: (1, 6, 50257) | unchanged at initialisation: True
Each block's c_attn maps the width-2 hidden state to 6 numbers (query, key and value of width 2 side by side). A rank-4 adapter on it has numbers, 64 for the two blocks. The logits have shape (batch 1, 6 tokens, 50,257 vocabulary entries) and are exactly those of the base model before any training, because every lora_B starts at zero. Training then works like the BERT loop with labels=input_ids; on a real causal LM (the NLP course uses one) the usual targets are ["q_proj", "k_proj", "v_proj", "o_proj"] or "all-linear".
Pitfalls
- Wrong
target_modulesnames. Names differ by architecture (queryin BERT,q_projin Llama,c_attnin GPT-2). Printmodelor[n for n, _ in model.named_modules()]first; PEFT raises an error if nothing matches, but a too-broad pattern can silently adapt layers you did not mean to. - Forgetting the head. With a custom task type or model, add the new head to
modules_to_save, or it stays at its random initialisation and the accuracy stays near chance. - Full fine-tuning learning rate for LoRA. barely moves a LoRA adapter whose starts at zero; LoRA usually wants to .
- Shipping only the adapter without pinning the base. An adapter is a delta: it only works on the exact base checkpoint it was trained on. Record the base model's name and revision (PEFT writes the name into
adapter_config.json). - Merging and then training again as if it were LoRA. After
merge_and_unload()the model is an ordinary model with all weights trainable; wrap it again if you want a new adapter. - Comparing on one seed and 500 sentences. One sentence is 0.002 of accuracy and a seed can move a run by more than that; claim differences only when they are larger than the noise.
Practice
- With
r=16instead of 8 on query and value, how many trainable parameters would the first example report? - You serve one base model to three customers, each with its own adapter. What do you store per customer, and why not merge?
- Why does
print_trainable_parameters()report slightly more "all params" (4,394,628) after wrapping than the plain model has?
Answers
- Each adapted 128 x 128 layer gets ; 4 layers give 16,384, plus the 258 head parameters: 16,642.
- Only each customer's adapter (tens of KiB here, tens of MB for a 7B model) and a note of the base revision. Merging would make three full copies of the model; unmerged adapters can be swapped per request on one copy in memory.
- The LoRA matrices themselves (8,192) are added to the model, so the total grows by that much: , where the extra 258 is the trainable copy of the head kept in
modules_to_savenext to the original.
Test yourself
What does modules_to_save do in a PEFT config?
- Saves the base model to disk
- Lists modules, such as a new classification head, that are trained in full and stored with the adapter
- Freezes the listed modules
- Quantises the listed modules
What is in the directory written by model.save_pretrained() for a PEFT model?
- The full model weights
- The adapter weights and its config (rank, alpha, target modules, base model name)
- Only the tokenizer
- The optimiser state
After merge_and_unload(), what is true?
- The model needs PEFT to run
- The LoRA layers are gone and the update is folded into ordinary weights, giving the same outputs up to rounding
- The adapter is deleted and the model reverts to the base
- The model is quantised