LoRA and Efficient Fine-Tuning

Updated · 13 min read
hardPython 3.13aillmlorapeftfine-tuningevaluation

LoRA (low-rank adaptation) is the most popular way to fine-tune large models cheaply. Instead of changing a big weight matrix W, it freezes W and learns a small correction B × A, where A and B are thin matrices. Only those small matrices are trained, often less than 1% of the parameters, so fine-tuning fits on a laptop or a single GPU, and the result is a small file that can be added to the original model.

This lesson completes the chapter's checkpoint: fine-tune a small open model to answer in Campus Helper's style, and show with an evaluation whether it beat prompting.

How LoRA Works

PartDescription
Frozen weights WThe pretrained matrix, for example 576 × 576; it doesn't change
Matrix AIt is used to squeeze each input down to r numbers (r × 576), started with small random values
Matrix BIt is used to expand those r numbers back to 576 (576 × r), started at zero
Rank rThe size of the squeeze, often 4 to 64; bigger means more capacity and more parameters
AlphaIt is used to scale the correction: the layer computes W·x + (alpha / r)·B·A·x
AdapterThe saved A and B matrices, which can be loaded on top of the original model or merged into it

Other parameter-efficient fine-tuning (PEFT) methods exist, but LoRA and QLoRA (LoRA on a model stored in 4-bit numbers to save memory) are the most widely used.

Example: LoRA by Hand

This program builds one LoRA correction with NumPy, using SmolLM2-135M's width of 576.

Python
import numpy as np
 
rng = np.random.default_rng(0)
d, r = 576, 8                                  # SmolLM2-135M's width, and the LoRA rank
 
W = rng.normal(size=(d, d))                    # a frozen pretrained weight matrix (q_proj is 576 x 576)
A = rng.normal(size=(r, d)) * 0.01             # LoRA's two small trainable matrices
B = np.zeros((d, r))                           # B starts at zero, so training starts from the original model
 
print("Full matrix:", W.shape, f"= {W.size:,} weights")
print("LoRA A and B:", A.shape, "and", B.shape, f"= {A.size + B.size:,} weights",
      f"({(A.size + B.size) / W.size:.1%} of the full matrix)")
 
x = rng.normal(size=d)                         # one token's 576 numbers
alpha = 16
print("\nAt the start, output changes by:", np.abs((alpha / r) * B @ (A @ x)).max())
 
B = rng.normal(size=(d, r)) * 0.01             # pretend training has updated B
delta = (alpha / r) * B @ A                    # the change LoRA adds to W
print("After training, the change B @ A has rank", np.linalg.matrix_rank(delta), "of a possible", d)
print("New output = W @ x + change @ x; largest change:", round(np.abs(delta @ x).max(), 4))
 
merged = W + delta                             # for deployment the change can be merged into W
print("Merged output equals W @ x + change @ x:", np.allclose(merged @ x, W @ x + delta @ x))
Output
Full matrix: (576, 576) = 331,776 weights
LoRA A and B: (8, 576) and (576, 8) = 9,216 weights (2.8% of the full matrix)
 
At the start, output changes by: 0.0
After training, the change B @ A has rank 8 of a possible 576
New output = W @ x + change @ x; largest change: 0.0388
Merged output equals W @ x + change @ x: True

Explanation:

  • The full matrix has 331,776 weights; A and B together have 9,216, only 2.8%. In the real model the saving is larger, because LoRA is added to only some layers.
  • B starts at zero, so at the start the correction is exactly 0 and the model behaves exactly like the original. Training then moves B and A away from zero.
  • The correction B @ A has rank 8: it can only change the layer in 8 independent directions out of 576. The idea behind LoRA is that adapting to a new task needs only a few directions of change.
  • For deployment, the correction can be merged into W, so the fine-tuned model runs exactly as fast as the original.

Example: The Checkpoint

The programs in this chapter need pip install torch transformers peft scikit-learn. They use SmolLM2-135M-Instruct, the small open model from "Instruction Tuning and RLHF", which runs on an ordinary laptop. The download and loading messages are left out of the output shown. This program uses train.jsonl and test.jsonl from "Preparing Fine-Tuning Data". It scores three approaches on the 19 test questions, which come from 15 FAQ entries and 4 unanswerable questions the model never trained on:

  1. Prompting: a clear system prompt describing the Campus Helper rules.
  2. Prompting with 2 examples: the same system prompt plus two worked examples, one answer and one decline (few-shot prompting).
  3. LoRA fine-tuning on the 43 training examples, with no system prompt.

A reply is correct if it cites the right FAQ entry and repeats at least 80% of its words, or gives the exact decline when no document answers. Format counts replies that follow the Campus Helper pattern, right or wrong.

A tiny trainable add-on: the format learned perfectly, the declines not yet
Python
import json
import re
 
import torch
from peft import LoraConfig, get_peft_model
from transformers import AutoModelForCausalLM, AutoTokenizer
 
NAME = "HuggingFaceTB/SmolLM2-135M-Instruct"
DECLINE = "I couldn't find that in the school's documents. Please contact the school office."
SYSTEM = ("You are Campus Helper, the school's assistant. Answer the parent's question using only the documents. "
          "Reply with the one document sentence that answers it, then (Source: FAQ #number). "
          "If no document answers it, reply exactly: " + DECLINE)
train = [json.loads(line) for line in open("train.jsonl")]   # from "Preparing Fine-Tuning Data"
test = [json.loads(line) for line in open("test.jsonl")]
tokenizer = AutoTokenizer.from_pretrained(NAME)
 
def words(text):
    return set(re.findall(r"[a-z0-9]+", text.lower()))
 
def grade(reply, expected):
    """Format: the Campus Helper pattern. Correct: right entry and facts, or a decline when it should."""
    formatted = reply == DECLINE or re.fullmatch(r".+ \(Source: FAQ #\d+\)", reply) is not None
    if expected == DECLINE:
        return formatted, reply == DECLINE
    sentence, source = expected.split(" (Source: ")
    overlap = len(words(sentence) & words(reply)) / len(words(sentence))
    return formatted, source in reply and overlap >= 0.8
 
def evaluate(model, system=None, shots=()):
    model.eval()
    scores = {"format": 0, "answers": 0, "declines": 0}
    for row in test:
        messages = ([{"role": "system", "content": system}] if system else []) + list(shots) + row["messages"][:1]
        ids = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt",
                                            return_dict=True)["input_ids"]
        with torch.no_grad():
            out = model.generate(ids, max_new_tokens=60, do_sample=False, pad_token_id=tokenizer.eos_token_id)
        reply = tokenizer.decode(out[0, ids.shape[1]:], skip_special_tokens=True).strip()
        expected = row["messages"][1]["content"]
        formatted, correct = grade(reply, expected)
        scores["format"] += formatted
        scores["declines" if expected == DECLINE else "answers"] += correct
    return scores
 
def report(name, s):
    total = s["answers"] + s["declines"]
    print(f"{name:28} format {s['format']:2}/19   answers {s['answers']:2}/15   declines {s['declines']}/4"
          f"   correct {total:2}/19 ({total / 19:.0%})")
 
torch.manual_seed(0)
model = AutoModelForCausalLM.from_pretrained(NAME, dtype=torch.float32)
report("Prompting (system prompt)", evaluate(model, SYSTEM))
# Few-shot: two worked examples from the training data, one answer and one decline, before the question
shots = next(r for r in train if r["messages"][1]["content"] != DECLINE)["messages"] + \
        next(r for r in train if r["messages"][1]["content"] == DECLINE)["messages"]
report("Prompting + 2 examples", evaluate(model, SYSTEM, shots))
 
# LoRA: freeze the model, add small trainable matrices to the attention layers
config = LoraConfig(r=8, lora_alpha=16, lora_dropout=0.0, task_type="CAUSAL_LM",
                    target_modules=["q_proj", "k_proj", "v_proj", "o_proj"])
model = get_peft_model(model, config)
trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
print(f"\nLoRA trains {trainable:,} parameters ({trainable / sum(p.numel() for p in model.parameters()):.2%})")
 
def encode(row):
    """Token IDs for the whole conversation; labels only on the assistant's reply."""
    prompt = tokenizer.apply_chat_template(row["messages"][:1], add_generation_prompt=True, tokenize=False)
    full = tokenizer.apply_chat_template(row["messages"], tokenize=False)
    p, f = tokenizer(prompt).input_ids, tokenizer(full).input_ids
    return torch.tensor([f]), torch.tensor([[-100] * len(p) + f[len(p):]])   # -100 = don't learn this token
 
examples = [encode(row) for row in train]
optimizer = torch.optim.AdamW([p for p in model.parameters() if p.requires_grad], lr=0.002)
for epoch in range(1, 5):
    model.train()
    total = 0.0
    for i in torch.randperm(len(examples)).tolist():
        ids, labels = examples[i]
        loss = model(input_ids=ids, labels=labels).loss
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        total += loss.item()
    print(f"epoch {epoch}: average loss {total / len(examples):.4f}")
 
print()
report("Fine-tuned with LoRA", evaluate(model))
model.save_pretrained("campus-helper-lora")      # saves only the small LoRA weights
Output
Prompting (system prompt)    format  0/19   answers  0/15   declines 0/4   correct  0/19 (0%)
Prompting + 2 examples       format 19/19   answers  0/15   declines 4/4   correct  4/19 (21%)
 
LoRA trains 921,600 parameters (0.68%)
epoch 1: average loss 0.4038
epoch 2: average loss 0.0437
epoch 3: average loss 0.0466
epoch 4: average loss 0.0326
 
Fine-tuned with LoRA         format 19/19   answers 11/15   declines 1/4   correct 12/19 (63%)

Explanation:

ApproachFormatAnswers rightDeclines rightCorrect
Prompting0/190/150/40/19
Prompting + 2 examples19/190/154/44/19
LoRA fine-tuned19/1911/151/412/19 (63%)
  • Prompting alone fails completely. This small model ignores the format and rambles, sometimes mixing up facts. A much bigger model would follow the same prompt far better.
  • Two examples fix the format but break the task: the model copies the decline for every question, even answerable ones. Its 4 points all come from the 4 questions that really needed a decline.
  • LoRA trains only 921,600 parameters (0.68%): rank-8 matrices on the four attention layers in each of the 30 blocks. The loss falls from 0.4038 to 0.0326 in four passes over 43 examples, in under a minute on a laptop CPU.
  • The fine-tuned model follows the format every time and gets 11 of 15 answers right on documents it has never seen. So fine-tuning beat prompting here, which is the checkpoint's question.
  • But it declines only 1 of 4 times. With only 8 decline examples among 43, it learned that answering is almost always right. That is the balance problem the data checks flagged; it would also need many more test questions before trusting it with parents.
  • labels of -100 mark the prompt tokens, so the loss is computed only on the reply: the model learns to write answers, not to predict the documents.
  • save_pretrained() saves only the adapter: 3.6 MB, against about 270 MB for the model.

With the seeds and data in these programs, the results are the same every run on the same machine and library versions.

Example: Using the Adapter

This program loads the saved adapter on top of the original model and asks three new questions.

Python
from peft import PeftModel
from transformers import AutoModelForCausalLM, AutoTokenizer
 
name = "HuggingFaceTB/SmolLM2-135M-Instruct"
tokenizer = AutoTokenizer.from_pretrained(name)
base = AutoModelForCausalLM.from_pretrained(name)
model = PeftModel.from_pretrained(base, "campus-helper-lora")   # the adapter saved by the checkpoint
model.eval()
 
documents = ("[FAQ #44] After-school tutoring is free on Mondays and Thursdays in the library.\n"
             "[FAQ #6] Cash payments are accepted at the school office from 8 a.m. to 3 p.m.\n"
             "[FAQ #27] Fall term begins on August 18.")
for question in ["Which days is tutoring?", "When does fall term start?", "Can I bring my dog to school?"]:
    messages = [{"role": "user", "content": f"Documents:\n{documents}\n\nQuestion: {question}"}]
    ids = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt",
                                        return_dict=True)["input_ids"]
    out = model.generate(ids, max_new_tokens=60, do_sample=False, pad_token_id=tokenizer.eos_token_id)
    print(question, "->", tokenizer.decode(out[0, ids.shape[1]:], skip_special_tokens=True).strip())
Output
Which days is tutoring? -> After-school tutoring is free on Mondays and Thursdays in the library. (Source: FAQ #44)
When does fall term start? -> Fall term begins on August 18. (Source: FAQ #6)
Can I bring my dog to school? -> After-school tutoring is free on Mondays and Thursdays in the library. (Source: FAQ #44)

Explanation: PeftModel.from_pretrained() adds the 3.6 MB adapter to the downloaded model. The tutoring answer is perfect. The fall term answer has the right sentence but cites FAQ #6 instead of #27, and the dog question, which no document answers, gets the tutoring sentence instead of a decline. These are exactly the weaknesses the evaluation predicted, which is why you measure before you ship.

Common Mistakes

Training on the prompt tokens too. The model wastes effort learning to predict documents; mask them with -100.

A learning rate that is too high or too low. LoRA often uses 1e-4 to 2e-3; check the loss falls smoothly and the test score improves.

Judging by training loss. A loss of 0.03 says the model copied the training replies, not that it generalizes; only the test set shows that.

Comparing against a weak prompt. Give prompting its best chance (rules plus examples) so the comparison is fair.

Interview Corner

How does LoRA work, and why is it efficient?

LoRA freezes the pretrained weights and learns a low-rank update B·A for selected layers, so only a small fraction of parameters is trained. That cuts memory and storage, and the adapter can be merged into the weights so inference is no slower.

How would you show that fine-tuning helped?

Score the base model with the best prompt you can write, and the fine-tuned model, on the same held-out test set with clear criteria. Report each kind of case separately, as answers and declines here, not just one average.

Practice

Exercise: rank and layers. Change r=8 to r=2 and then r=32, and try adding "up_proj", "down_proj" to target_modules. How do the trainable parameters and the test scores change?

Check your understanding:

  1. Why does B start at zero?
  2. Why did prompting with two examples get every answerable question wrong?
  3. What would you change to improve the declines?

Quick check: LoRA

4 questions
1How many parameters did LoRA train in the checkpoint?
2How many of the 19 test questions did the fine-tuned model get right?
3Why does LoRA start with B at zero?
4What was the fine-tuned model's main weakness?

Key Takeaways

Quick reference

NeedCode
LoRA settingsLoraConfig(r=8, lora_alpha=16, target_modules=["q_proj", "v_proj"], task_type="CAUSAL_LM")
Add LoRA to a modelmodel = get_peft_model(model, config)
Count trainable parametersmodel.print_trainable_parameters()
Learn only the replylabels of -100 for prompt tokens
Save the adaptermodel.save_pretrained("folder")
Load it laterPeftModel.from_pretrained(base_model, "folder")
Merge for deploymentmodel.merge_and_unload()

Was this tutorial helpful?

Lesson 153 of 186