Sub topic 6
Adding a LoRA adapter with PEFT
This chapter assumes you can load a Hugging Face transformers causal language model and run inference. It also assumes you know the LoRA update W + (alpha/r)BA and what rank, alpha, dropout and target modules control. Here you attach an adapter to a real model with the PEFT library and check what is trainable.
What PEFT does
PEFT (Parameter-Efficient Fine-Tuning) is a Hugging Face library that wraps a base model and injects small trainable modules into it. For LoRA, it finds the linear layers you name, replaces each one with a LoRA-wrapped version, and freezes everything else. You write a configuration and make one function call. You don't edit the model code.
The wrapped layer works like the hand-written layer below. The base weight is frozen, A and B are trained, and B starts at zero. At the start of training the layer therefore returns exactly what the base layer returns.
import torch
import torch.nn as nn
class LoRALinear(nn.Module):
def __init__(self, base: nn.Linear, r: int = 8, alpha: int = 16):
super().__init__()
self.base = base
for p in self.base.parameters():
p.requires_grad_(False)
self.A = nn.Parameter(torch.randn(r, base.in_features) * 0.01)
self.B = nn.Parameter(torch.zeros(base.out_features, r))
self.scale = alpha / r
def forward(self, x):
return self.base(x) + (x @ self.A.T @ self.B.T) * self.scale
layer = LoRALinear(nn.Linear(64, 64), r=4, alpha=8)
print(sum(p.numel() for p in layer.parameters() if p.requires_grad))This prints 512, which is 4*64 + 64*4. The full 64 by 64 weight has 4,096 values, so the adapter trains one eighth of them.
Configure and attach the adapter
LoraConfig holds the hyperparameters. get_peft_model applies them.
from transformers import AutoModelForCausalLM
from peft import LoraConfig, get_peft_model
model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct")
lora_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, lora_config)
model.print_trainable_parameters()The call to print_trainable_parameters() reports the trainable count, the total count and the percentage. For this setup the trainable share is well under 2 percent of the total.
Choosing the settings in the config
ris the rank. It sets the size ofAandBand so the adapter's capacity and memory cost.lora_alphasets the scalealpha/r. Withr=16andlora_alpha=32the scale is 2.lora_dropoutapplies dropout to the input of the adapter path during training. It acts as a mild regularizer.target_moduleslists the layer names to adapt. The names match the module names in the model, so they differ between architectures.task_typetells PEFT how the model is used."CAUSAL_LM"is correct for decoder-only chat models.
To find valid names for a new model, list its linear layers:
import torch.nn as nn
from transformers import AutoModelForCausalLM
model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct")
names = {n.split(".")[-1] for n, m in model.named_modules() if isinstance(m, nn.Linear)}
print(sorted(names))For Qwen2.5 this lists the attention projections (q_proj, k_proj, v_proj, o_proj), the MLP projections (gate_proj, up_proj, down_proj) and lm_head. You can also pass target_modules="all-linear", which adapts every linear layer except the output head.
Common errors
- "Target modules not found." The names in
target_modulesdon't exist in this model. Print the layer names as shown above and copy them exactly. - Zero trainable parameters. The model was frozen or loaded in a way that blocked training. Check that you used the object returned by
get_peft_model, not the original model. - Wrong
task_type. An encoder model with"CAUSAL_LM"wraps it with the wrong head logic. Match the task to the model.
Exercise
A model has a 1024 by 1024 linear layer. You adapt it with r=8. How many trainable parameters does LoRA add for that layer, and what fraction of the layer's weights is that?
Show answer
A has shape 8 by 1024 and B has shape 1024 by 8, so the adapter adds 81024 + 10248 = 16,384 parameters. The layer has 1,048,576 weights, so the adapter is about 1.6 percent of it.
Exercise
Why does the adapted model give the same outputs as the base model before any training step?
Show answer
B is initialized to zeros, so the product BA is zero. The scaled update added to the base output is therefore zero.