Full fine-tuning updates every weight in a model. For a 7-billion-parameter model that means storing the weights, their gradients and the optimiser state — far more memory than a single consumer GPU has. LoRA (Low-Rank Adaptation) gets around this by training a tiny add-on instead.
The idea in one equation
For a weight matrix W of shape d × d, LoRA freezes W and learns two small matrices A (d × r) and B (r × d), with a rank r like 8 or 16. The layer's output becomes:
W·x + B·A·x
With d = 4096 and r = 16, the adapter (A plus B) has about 131k parameters instead of the 16.8 million in W. You train well under 1% of the model.
The memory maths
| Item | Full fine-tune (7B) | LoRA on a 4-bit base |
|---|---|---|
| Base weights | ~14 GB (16-bit) | ~4 GB (4-bit) |
| Gradients + optimiser | ~50+ GB | well under 1 GB (adapters only) |
| Fits on a 24 GB GPU? | No | Yes, with room for activations |
Quantising the frozen base to 4 bits while training LoRA adapters on top is known as QLoRA.
A minimal recipe
# pip install transformers peft trl datasets bitsandbytes accelerate
import torch
from datasets import load_dataset
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
from peft import LoraConfig
from trl import SFTConfig, SFTTrainer
base = "mistralai/Mistral-7B-v0.1"
tokenizer = AutoTokenizer.from_pretrained(base)
model = AutoModelForCausalLM.from_pretrained(
base,
quantization_config=BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_compute_dtype=torch.bfloat16),
device_map="auto",
)
lora = LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05,
target_modules=["q_proj", "k_proj", "v_proj", "o_proj"], task_type="CAUSAL_LM")
data = load_dataset("json", data_files="train.jsonl", split="train") # {"text": "..."} per line
trainer = SFTTrainer(
model=model,
train_dataset=data,
peft_config=lora,
processing_class=tokenizer,
args=SFTConfig(output_dir="out", per_device_train_batch_size=2, gradient_accumulation_steps=8,
num_train_epochs=2, learning_rate=2e-4, logging_steps=10, bf16=True),
)
trainer.train()
trainer.save_model("out/adapter")Library APIs move quickly; check the current trl and peft docs if an argument name has changed.
Choosing the settings
- Rank
r: 8–16 is enough for style and format; go higher for new knowledge-heavy tasks. - Target modules: attention projections are the classic choice; adding the MLP layers often helps a bit more.
- Data beats settings. A few hundred clean, consistent examples usually do more than any hyper-parameter tweak.
When not to fine-tune
If you need the model to know facts that change, use retrieval (RAG) instead. Fine-tuning is best for teaching a behaviour: a format, a tone, a classification scheme, a domain's vocabulary.
Takeaways
- LoRA trains small adapters while the base model stays frozen.
- Quantising the base (QLoRA) makes 7B models trainable on one 24 GB GPU.
- Use fine-tuning for behaviour, retrieval for knowledge.