Sub topic 6
Adding a LoRA adapter with PEFT
This chapter shows how to attach a LoRA adapter to a pretrained causal language model with Hugging Face PEFT. It assumes you know basic PyTorch, have run a transformers model for inference, and have read the earlier chapters on the LoRA update W + (alpha/r)BA and on rank, alpha, dropout and target modules. The next chapter covers training.
What PEFT does for you
In an earlier chapter you saw a hand-written LoRALinear layer that froze a base weight and added two small matrices. PEFT (Parameter-Efficient Fine-Tuning) automates the same steps for a whole model:
- It walks the model and finds the layers named in
target_modules. - It replaces each of those layers with a LoRA-aware version that holds the original weight plus matrices A and B.
- It sets
requires_grad=Falseon every base parameter and leaves only the adapter parameters trainable. - It returns a
PeftModelwrapper that tracks the adapter configuration, so you can save, load, disable or merge the adapter later.
The basic setup
This is the standard setup for a small instruction-tuned model.
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 last line prints the trainable count, the total count and the percentage. For this model and configuration the trainable count is about 2.16 million, roughly 0.4% of the total. Your exact numbers depend on the library version, but the fraction should be well under 1%. If it prints 100%, or 0 trainable parameters, something is wrong (see the troubleshooting section).
Reading the LoraConfig fields
| Field | What it controls | Practical note |
|---|---|---|
| `r` | Rank of A and B | Higher rank means more capacity and more trainable parameters. 8 to 64 is a common range. |
| `lora_alpha` | Numerator of the scale `alpha/r` | With `r=16` and `lora_alpha=32` the update is multiplied by 2. |
| `lora_dropout` | Dropout applied to the input of the adapter path | The base path is not affected. 0.0 to 0.1 is typical. |
| `target_modules` | Which layers get adapters | Names are matched against module names, not full paths. |
| `task_type` | Tells PEFT which model wrapper to build | Use `"CAUSAL_LM"` for decoder-only language models. |
| `bias` | Whether to train bias terms | `"none"` is the default and usually right. |
| `modules_to_save` | Extra modules trained in full and saved with the adapter | Use for new heads or resized embeddings. |
The number of trainable parameters is easy to predict. A LoRA adapter on a layer with in inputs and out outputs adds r * (in + out) parameters. Rank 16 on a 896-to-896 projection adds 16 × 1792 = 28,672 parameters, whereas the base projection has 802,816 weights.
Finding the right target module names
Module names differ between architectures. Llama, Mistral and Qwen models use q_proj, k_proj, v_proj and o_proj for attention. They use gate_proj, up_proj and down_proj in the MLP. GPT-2 uses c_attn. Rather than guess, list the linear layers in your model.
import torch.nn as nn
from transformers import AutoModelForCausalLM
model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct")
names = {
name.split(".")[-1]
for name, module in model.named_modules()
if isinstance(module, nn.Linear)
}
print(sorted(names))For Qwen2.5 this prints ['down_proj', 'gate_proj', 'k_proj', 'lm_head', 'o_proj', 'q_proj', 'up_proj', 'v_proj']. Choose from this list. Do not target lm_head unless you have a reason, because it holds a large matrix (vocabulary size by hidden size) and usually shares weights with the input embeddings.
You have three common choices:
- Attention only:
["q_proj", "k_proj", "v_proj", "o_proj"]. Cheap, and often enough for style or format changes. - Attention plus MLP: add
gate_proj,up_projanddown_proj. More capacity and more memory, and often better for learning new knowledge or tasks. target_modules="all-linear". PEFT targets every linear layer except the output head. This is what the QLoRA example in a later chapter uses.
If a name matches nothing, PEFT raises a ValueError saying the target modules were not found in the base model. That error almost always means a typo or a name copied from a different architecture.
Inspecting what was added
After wrapping, look at the parameter names to confirm the structure.
for name, param in model.named_parameters():
if param.requires_grad:
print(name, tuple(param.shape))
breakThe first line printed looks like base_model.model.model.layers.0.self_attn.q_proj.lora_A.default.weight (16, 896). Three details are worth reading:
lora_Ahas shape(r, in_features)andlora_Bhas shape(out_features, r), matching the math from earlier chapters.defaultis the adapter name. A single model can hold several adapters under different names.- PEFT initializes A with a small random (Kaiming uniform) distribution and B with zeros. At step 0 the product BA is zero, so the wrapped model produces the same outputs as the base model.
You can verify the last point directly. Compare logits with the adapter on and off.
import torch
from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct")
inputs = tok("Low-rank adaptation is", return_tensors="pt")
model.eval()
with torch.no_grad():
with_adapter = model(**inputs).logits
with model.disable_adapter():
without_adapter = model(**inputs).logits
print(torch.allclose(with_adapter, without_adapter, atol=1e-5))Before any training this prints True. After training it prints False, and the disable_adapter() context manager becomes a convenient way to get base-model outputs from the same loaded model, which you will use when evaluating against the base.
Choosing dtype and device before wrapping
The base model's dtype sets the memory cost of the frozen weights. Loading in torch.bfloat16 halves the memory of the default float32 load. PEFT creates adapter weights in the dtype of the base layer in some versions and in float32 in others, depending on its autocast settings, so check model.dtype and a sample adapter parameter's dtype if memory matters.
import torch
from transformers import AutoModelForCausalLM
model = AutoModelForCausalLM.from_pretrained(
"Qwen/Qwen2.5-0.5B-Instruct",
torch_dtype=torch.bfloat16,
)Optimizer states (Adam keeps two extra tensors per trainable parameter) exist only for adapter weights. This is where most of the memory saving over full fine-tuning comes from: gradients and optimizer states for about 0.4% of the parameters.
Gradient checkpointing
Gradient checkpointing trades compute for memory by recomputing activations during the backward pass. With a frozen base model there is a catch. The input embeddings are frozen, so the checkpointed blocks receive inputs that do not require gradients, and the backward pass can fail or silently train nothing. The fix is one line before wrapping:
model.gradient_checkpointing_enable()
model.enable_input_require_grads()When you train with SFTTrainer and gradient_checkpointing=True in the config, the trainer handles this for PEFT models in recent versions. If you write your own training loop, call it yourself.
Common errors and how to read them
| Symptom | Likely cause | Fix |
|---|---|---|
| `ValueError: Target modules ... not found in the base model` | Wrong module names for this architecture | List linear layers as shown above and copy exact names. |
| `trainable params: 0` | Adapter parameters were frozen after wrapping, or the model was loaded in a mode that froze them | Do not call `requires_grad_(False)` on the whole `PeftModel`. Load a saved adapter with `is_trainable=True` when continuing training. |
| Loss does not change at all | Gradients are not reaching the adapters, often with gradient checkpointing | Call `enable_input_require_grads()` before wrapping. |
| Adapter works in training but outputs look like the base model later | The adapter was disabled or never loaded | Check for a leftover `disable_adapter()` context and confirm the adapter path. |
| Very large trainable percentage | `modules_to_save` or `lm_head` and embeddings were included | Remove them unless you need them. |
A checklist before you train
- The base model loads and generates sensible text without the adapter.
target_modulescame from the real module list, not memory.print_trainable_parameters()shows a small fraction, typically 0.1% to 2%.- With the adapter freshly initialized, outputs match the base model.
- If you use gradient checkpointing, input gradients are enabled.
Exercise
A model has a linear layer with 2048 inputs and 2048 outputs. You attach LoRA with r=8 to it. How many adapter parameters does that layer gain, and how does it compare with the 2048 × 2048 base weight? Why does a freshly created adapter leave the model's outputs unchanged?
Show answer
The adapter adds r × (in + out) = 8 × (2048 + 2048) = 32,768 parameters. The base weight has 4,194,304, so the adapter is about 0.78% of it. The outputs are unchanged because PEFT initializes B with zeros, so the product BA is a zero matrix and the layer computes W x plus zero.
Exercise
You wrap a model with target_modules=["query", "value"] and get a ValueError that the target modules were not found. What is the most likely cause, and what code would you run to find the correct names?
Show answer
The names come from a different architecture. Qwen, Llama and Mistral use qproj, kproj, vproj and oproj instead. List the linear layers with {n.split(".")[-1] for n, m in model.named_modules() if isinstance(m, nn.Linear)} and choose names from that set.