Sub topic 10
Parameter-efficient tuning with LoRA
This chapter assumes you have read the previous chapters on fine-tuning and training data. You should know that full fine-tuning updates every weight in a model. You should also be comfortable reading short Python snippets and know what a matrix is.
Full fine-tuning is the most expensive way to change behavior. Parameter-efficient fine-tuning (PEFT) trains a small number of new parameters and leaves the original model untouched. The most common PEFT method is LoRA, short for Low-Rank Adaptation. This chapter explains how LoRA works, what it costs, when it is the right choice, and where it fails.
Why full fine-tuning is often too heavy
Fine-tuning a model with billions of weights has three costs beyond the training run itself.
- Memory. Training needs more than the weights. The optimizer keeps extra state for every trainable weight. With the Adam optimizer, that is typically two additional values per weight, plus gradients. Training memory is often several times the memory needed to serve the model.
- Storage. Each fine-tuned variant is a full copy of the model. Ten variants for ten customers means ten full copies.
- Risk. Changing every weight can erode general abilities the base model had. This is called catastrophic forgetting.
PEFT methods address all three by training a small add-on instead of the whole model. They do not change what fine-tuning is for. It still shapes behavior (style, format, task habits) and is a poor way to add facts, as the earlier chapters covered.
The core idea: a low-rank update
A weight matrix W in a transformer layer has shape d_out × d_in. Full fine-tuning learns a change ΔW of the same shape, so the final weight is W + ΔW.
LoRA makes one assumption: the useful change ΔW can be well approximated by a matrix of low rank. A low-rank matrix is the product of two thin matrices. LoRA therefore freezes W and learns two small matrices instead:
Awith shaper × d_inBwith shaped_out × r
The number r is the rank, usually between 4 and 64. The update is ΔW = (alpha / r) · B · A, where alpha is a scaling constant you choose. The layer's output becomes:
y = W·x + (alpha / r) · B·(A·x)
Two details matter in practice:
Bis initialized to zeros andAto small random values. At step zero,B·Ais zero, so the adapted model behaves exactly like the base model. Training starts from the base model's behavior.- Only
AandBreceive gradients.Wstays frozen.
Counting the savings
The parameter count shows why this is cheap. For a single d × d matrix:
- Full update:
d × dparameters. - LoRA update:
r × d + d × r = 2·r·dparameters.
The following script builds one LoRA layer with NumPy, checks that it starts identical to the base layer, and prints the counts.
import numpy as np
d_in, d_out, r, alpha = 1024, 1024, 8, 16
rng = np.random.default_rng(0)
W = rng.normal(size=(d_out, d_in)) # frozen base weight
A = rng.normal(scale=0.01, size=(r, d_in)) # trainable, small random init
B = np.zeros((d_out, r)) # trainable, zero init
def lora_forward(x):
return W @ x + (alpha / r) * (B @ (A @ x))
x = rng.normal(size=(d_in,))
assert np.allclose(lora_forward(x), W @ x) # B is zero, so output matches base
full_params = d_out * d_in
lora_params = r * d_in + d_out * r
print(f"full update: {full_params:,} parameters")
print(f"LoRA update: {lora_params:,} parameters ({lora_params / full_params:.2%})")This prints 1,048,576 for the full update and 16,384 for LoRA, about 1.56%. On larger matrices the share is smaller. For d = 4096 and r = 8, LoRA trains 65,536 parameters instead of about 16.8 million per matrix, under 0.4%.
Applied across a whole model, adapters typically amount to well under 1% of the base parameter count. An adapter file is often tens of megabytes, where a full model copy is many gigabytes.
Using LoRA with the Hugging Face PEFT library
The peft library wraps a Hugging Face model and injects the adapters. This sketch configures LoRA on a small model. It needs transformers and peft installed and downloads the model weights on first run.
from transformers import AutoModelForCausalLM
from peft import LoraConfig, get_peft_model
base = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct")
config = LoraConfig(
r=8,
lora_alpha=16,
lora_dropout=0.05,
target_modules=["q_proj", "v_proj"],
task_type="CAUSAL_LM",
)
model = get_peft_model(base, config)
model.print_trainable_parameters()print_trainable_parameters() reports how many parameters are trainable and what percentage of the total they are. Check this number every time. If it shows 100%, the adapters were not applied as you intended.
From here you train with your usual loop or trainer on the chat-format JSONL data described in the training data chapter. After training, model.save_pretrained("my-adapter") writes only the adapter weights.
The settings that matter
| Setting | What it controls | Typical starting point |
|---|---|---|
| `r` (rank) | Capacity of the update. Higher rank can learn more but costs more and overfits more easily. | 8 to 16 |
| `lora_alpha` | Scale of the update. The effective scale is `alpha / r`. | Equal to `r` or `2 × r` |
| `target_modules` | Which weight matrices get adapters. | Attention projections, or all linear layers |
| `lora_dropout` | Regularization on the adapter path. | 0.0 to 0.1 |
| Learning rate | Step size for the adapter weights. LoRA usually tolerates a higher rate than full fine-tuning. | Around 1e-4 to 2e-4 |
Treat these as starting values to validate against your evaluation set, not as fixed rules. If you raise r, remember that alpha / r changes unless you raise alpha with it.
Quantized variants: QLoRA
QLoRA combines LoRA with a quantized base model. Quantization stores the frozen weights in fewer bits, commonly 4, which cuts the memory needed to hold them. The adapters themselves stay in higher precision and are the only trained parameters. This makes it possible to fine-tune fairly large models on a single GPU.
The trade-off is some added complexity and a small quality gap in some tasks versus a full-precision base. If you serve the model quantized, train against that same quantized base so the adapter matches what runs in production.
Serving: merge or swap
An adapter can be used in two ways.
- Merge. Compute
W + (alpha / r)·B·Aonce and write the result back intoW. The merged model has the same architecture and size as the base, so inference has no extra latency. The cost is that you now have a full-size model file again. - Swap at runtime. Keep one base model in memory and load adapters on demand. Many serving stacks can apply different adapters to different requests on the same base. This suits a setup with one adapter per customer or per task. The cost is a small amount of extra computation per layer and more serving machinery.
Merging into a quantized base can introduce rounding error, so rerun your evaluation after merging.
Where LoRA fits in the decision
LoRA changes how you fine-tune, not whether you should. The decision framework from earlier chapters still comes first: keep prompting if it passes your evaluation, add RAG for missing or changing knowledge, and fine-tune for behavior prompts cannot fix. LoRA is the default way to do that third step when cost, memory, or the number of variants matters.
| Factor | Full fine-tuning | LoRA |
|---|---|---|
| Trainable parameters | All | Usually under 1% |
| Training memory | High | Much lower |
| Artifact per variant | Full model copy | Small adapter file |
| Ceiling on quality | Highest | Close for most behavior tasks, lower for large shifts |
| Risk of forgetting | Higher | Lower, since base weights are frozen |
| Switching tasks | Load a different model | Swap an adapter |
Full fine-tuning is still reasonable when you have a large, high-quality dataset and need a substantial shift in the model's abilities, such as a new language or a new domain with its own vocabulary.
Gotchas and failure modes
- Using LoRA to inject facts. An adapter trained on a document set may reproduce phrases but will answer questions about it unreliably, and it cannot be updated by editing a source file. Use RAG for knowledge.
- No baseline. A tuned adapter that was never compared against the best prompt on a held-out evaluation set proves nothing. The baseline you built earlier is what tells you whether the adapter earned its place.
- Overfitting on small data. With a few hundred examples and a high rank, the adapter can memorize the training set. Watch validation loss and task score, and stop when they stop improving.
- Wrong or inconsistent chat template. Training data must be formatted with the same template used at inference. A mismatch silently degrades results.
- Adapter and base mismatch. An adapter is only valid for the exact base model it was trained on. A new base version needs retraining. Record the base model name and revision next to every adapter.
- Stale behavior. Your product rules change, and the adapter does not. Plan to retrain on updated data and version adapters like any other release artifact.
- Merged-model regressions. Merging, especially into quantized weights, can shift outputs slightly. Evaluate the merged artifact, not just the adapter.
Summary of when to choose LoRA
Choose LoRA when all of these hold:
- Your evaluation shows a behavior gap that prompting and few-shot examples did not close.
- You have curated input and output examples of the behavior you want.
- You need lower memory use, small artifacts, or several task-specific variants on one base model.
If any of the three is missing, go back to prompting or RAG first.
Exercise
A team has a model with 7 billion parameters. They apply LoRA with r = 16 to a single 4096 × 4096 attention matrix. How many parameters does the adapter for that matrix have, how does that compare to the full matrix, and what are the values of A's and B's initial contents at step zero that make the model start out identical to the base?
Show answer
The adapter has r·(din + dout) = 16 × (4096 + 4096) = 131,072 parameters. The full matrix has 4096 × 4096 = 16,777,216 parameters, so the adapter is about 0.78% of it. B is initialized to all zeros and A to small random values, so B·A is zero and the output at step zero equals the base model's output.
Exercise
A company wants its support assistant to answer questions about a product manual that changes every month, and also to always reply in a fixed JSON format. Which approach would you use for each requirement, and where would LoRA fit?
Show answer
Use RAG for the manual, because the facts change monthly and retrieval lets you update them by re-indexing without retraining. Try prompting with few-shot examples for the JSON format first. If it fails your evaluation, train a LoRA adapter on example input and JSON output pairs, because format consistency is a behavior gap. The two can be combined: the adapter fixes the format and RAG supplies the facts.