Papa Programmer
Lesson 24 of 36

LoRA in code

9 min read

Optional

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.

python
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.

python
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:

text
['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,720

Reading the output teaches three things.

  • c_attn matches 12 layers, one per block, as intended.
  • c_proj matches 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 longer attn.c_proj narrows it to 12.
  • q_proj is 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:

  1. Print a tokenised batch and check the labels and masks, as Tokenisation for training describes.
  2. Run a few steps and confirm that the loss moves.
  3. 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:

  1. Load the same base model, with the same revision.
  2. Load the tokenizer and any chat template, as saved with the run.
  3. 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.

  1. LoadLoad the base model and tokenizer.
  2. ConfigureChoose rank, alpha and target modules.
  3. CheckCount matched layers and trainable parameters.
  4. TrainRun a short trial, then the full run.
  5. SaveStore the adapter, config, tokenizer and base model identity.
From model to saved adapter
Name layers carefullyShort names can match more layers than you meant, and wrong names match none.
Count before you trainMatched layers and trainable share expose most setup mistakes.
Keep a recordAn adapter needs its base model, tokenizer and configuration to be reproduced.

Your reading position is saved

0%

0 of 36 complete

Contents

Learning tools