LoRA and QLoRA: parameter-efficient fine-tuning

Low-rank adapters, their maths, PEFT code, 4-bit QLoRA on a single GPU, and merging adapters for deployment.

Expert about 6 h

The picture

  1. 01

    Freeze base

    W stays fixed

  2. 02

    Add B·A

    rank r adapters

  3. 03

    Train adapters

    few % of params

  4. 04

    Merge or swap

    W + BA

  5. 05

    Serve

    one base, many adapters

The idea

Updating every weight of a large model needs memory for gradients and optimiser state, several times the model size. LoRA freezes the original weight matrix W0∈Rd×kW_0\in\mathbb{R}^{d\times k} and learns a low-rank change:

W=W0+αr BA,B∈Rd×r, A∈Rr×k, r≪min⁡(d,k)W = W_0 + \frac{\alpha}{r}\,B A,\qquad B\in\mathbb{R}^{d\times r},\ A\in\mathbb{R}^{r\times k},\ r\ll\min(d,k)

BB starts at zero, so training begins exactly at the base model. Trainable parameters per matrix drop from dkdk to r(d+k)r(d+k). For a 4096×40964096\times4096 layer at r=16r=16 that is 131,072 instead of about 16.8 million, under 1 percent.

def lora_params(d, k, r):
    return r * (d + k), d * k

print(lora_params(4096, 4096, 16))        # (131072, 16777216)

LoRA with PEFT

import torch
from transformers import AutoModelForCausalLM
from peft import LoraConfig, get_peft_model

base = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-1.5B", torch_dtype=torch.bfloat16, device_map="auto")
cfg = LoraConfig(
    r=16, lora_alpha=32, lora_dropout=0.05,
    target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"],
    task_type="CAUSAL_LM",
)
model = get_peft_model(base, cfg)
model.print_trainable_parameters()        # well under 2% trainable

Then train with the same SFTTrainer as before, passing peft_config=cfg instead of wrapping the model yourself. Typical settings: rank 8 to 64, alpha about 2×rank, learning rate 1e-4 to 3e-4. Adapting all linear layers usually beats attention-only adapters.

QLoRA: a 4-bit base

QLoRA stores the frozen base in 4-bit NormalFloat, runs computation in bf16, and trains LoRA adapters on top, which lets a 7B to 13B model be tuned on a single consumer or mid-range GPU.

from transformers import BitsAndBytesConfig
from peft import prepare_model_for_kbit_training

bnb = BitsAndBytesConfig(
    load_in_4bit=True, bnb_4bit_quant_type="nf4",
    bnb_4bit_use_double_quant=True, bnb_4bit_compute_dtype=torch.bfloat16,
)
base = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-7B", quantization_config=bnb, device_map="auto")
base = prepare_model_for_kbit_training(base)
model = get_peft_model(base, cfg)

Use a paged optimiser (for example optim="paged_adamw_8bit" in the training arguments) to survive memory spikes.

What LoRA gives and costs

  • Pros: tiny checkpoints (megabytes), cheap training, many adapters on one base (serve per-customer variants), less forgetting.
  • Cons: it can learn less than full fine-tuning on tasks needing large behaviour change or new knowledge; rank and target modules need tuning.

Merging for deployment

from peft import PeftModel
base = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-1.5B", torch_dtype=torch.bfloat16)
merged = PeftModel.from_pretrained(base, "out/lora/final").merge_and_unload()
merged.save_pretrained("out/merged")

Merging removes inference overhead. Verify that merged outputs match the adapter model on a sample, and merge into a full-precision base, not a quantised one, then quantise afterwards.

Common mistakes

  • Merging an adapter trained on a 4-bit base into a different base version.
  • Raising the rank to fix a data-quality problem.
  • Forgetting that the adapter is tied to its exact base model and tokenizer.

Exercises

  1. Run LoRA at ranks 4, 16 and 64 on the same data and plot quality against trainable parameters.
  2. Train two adapters for two tasks and swap them at inference time on one loaded base.

You are done when you can…

  • Explain LoRA's update rule and compute the trainable-parameter count for a layer
  • Fine-tune a 7B-class model in 4-bit with QLoRA on one GPU
  • Merge an adapter into the base weights and verify outputs are unchanged