LoRA in code
9 min read
Attach an adapter
The Hugging Face PEFT library wraps a model so that only the adapter trains. You choose a rank, an alpha and the target modules. The example below attaches an adapter to GPT-2's attention projection. Install compatible versions of PyTorch, Transformers and PEFT first. The model downloads on the first run.
from peft import LoraConfig, TaskType, get_peft_model
from transformers import AutoModelForCausalLM
base = AutoModelForCausalLM.from_pretrained("openai-community/gpt2")
config = LoraConfig(
task_type=TaskType.CAUSAL_LM,
r=8,
lora_alpha=16,
target_modules=["c_attn"],
fan_in_fan_out=True,
)
model = get_peft_model(base, config)
model.print_trainable_parameters()The last line prints the trainable and total parameter counts. The exact text depends on your PEFT version, so this Lesson does not quote it. It also does not train anything yet: that needs tokenised data and a trainer, as in Fine-tune a model to follow instructions. The PEFT LoRA guide lists every option.
Check that the targets matched
PEFT matches target_modules against the model's layer names. A name matches when it equals a target or ends with a dot and the target. Wrong names are the most common mistake, and the results range from an error to an adapter that trains the wrong layers. The program below rebuilds the layer names of GPT-2 small, which has 12 blocks, and counts what each target list matches.
names = ["transformer.wte", "transformer.wpe"]
for block in range(12):
names += [
f"transformer.h.{block}.attn.c_attn",
f"transformer.h.{block}.attn.c_proj",
f"transformer.h.{block}.mlp.c_fc",
f"transformer.h.{block}.mlp.c_proj",
]
def matches(name, target):
return name == target or name.endswith("." + target)
for targets in [["c_attn"], ["c_proj"], ["attn.c_proj"], ["q_proj"]]:
hits = [n for n in names if any(matches(n, t) for t in targets)]
print(f"{str(targets):16} matches {len(hits)} layers")
rank, inputs, outputs, blocks = 8, 768, 2304, 12
trainable = blocks * rank * (inputs + outputs)
total = 124_439_808 + trainable
print(f"adapter on c_attn: {trainable:,} trainable, {trainable / total:.2%} of {total:,}")It prints:
['c_attn'] matches 12 layers
['c_proj'] matches 24 layers
['attn.c_proj'] matches 12 layers
['q_proj'] matches 0 layers
adapter on c_attn: 294,912 trainable, 0.24% of 124,734,720Reading the output teaches three things.
c_attnmatches 12 layers, one per block, as intended.c_projmatches 24, because both the attention block and the feed-forward block have a layer with that name. A short name can pick up more than you meant, and the longerattn.c_projnarrows it to 12.q_projis the name used by Llama-style models. On GPT-2 it matches nothing, and PEFT raises an error in that case. The same mistake in a longer list that has one valid name would pass without notice, so look at the counts.
The last two lines count the adapter: 12 blocks, each with a matrix of 768 inputs and 2,304 outputs. For rank 8 that is 294,912 trainable numbers, about a quarter of one percent of the model. The count PEFT prints should be close to this. A much smaller number means the targets missed layers. A number close to the whole model means the base weights are not frozen.
Train the adapter
Pass the adapted model to the same trainer you used before. Before the full run:
- Print a tokenised batch and check the labels and masks, as Tokenisation for training describes.
- Run a few steps and confirm that the loss moves.
- Record the PEFT and Transformers versions, the adapter configuration and the base model revision.
LoRA often tolerates a higher learning rate than full fine-tuning, as Learning rate, warm-up and schedules noted, so start from the documented value for your model.
Save and reload
Saving the model after training writes only the adapter, which is a small file plus its configuration. To use it later:
- Load the same base model, with the same revision.
- Load the tokenizer and any chat template, as saved with the run.
- Attach the saved adapter with PEFT's
PeftModel.from_pretrained.
If the base model differs from the one used for training, the adapter may load but give poor results, so keep an identifier of the base model next to the adapter.
Merge for serving
For supported models, PEFT can merge the adapter into the base weights, which removes the extra step at inference. After merging, save the result as a normal model. Keep the unmerged adapter and base too, so that you can swap or reproduce them. Some quantised formats do not support merging, so check yours first. The PEFT checkpoint guide has current details.
- LoadLoad the base model and tokenizer.
- ConfigureChoose rank, alpha and target modules.
- CheckCount matched layers and trainable parameters.
- TrainRun a short trial, then the full run.
- SaveStore the adapter, config, tokenizer and base model identity.
Which modules do you usually target?
You configure LoRA on a transformer.
Those layers are common targets, and the right names depend on the model.
What does print_trainable_parameters show?
You wrap a model with PEFT.
A tiny share of the total confirms the base is frozen.
What do you save after training?
Training has finished.
The adapter is small, and you need the same base model to use it.
Your reading position is saved
0 of 36 complete
Lesson complete
LoRA in code
Up next