Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Concept · 20 min · revision 2

LoRA and QLoRA: Training Millions of Parameters Instead of Billions

Why full fine-tuning needs so much GPU memory, how a LoRA adapter replaces a weight update with two small matrices, how rank, alpha, target modules and learning rate are chosen, what QLoRA adds with a 4-bit frozen base, and how preference tuning with DPO differs from supervised fine-tuning, each with a small script you can run on a CPU.

Contentsand lesson path

What you will learn

  • Run supervised fine-tuning with LoRA or QLoRA within a GPU memory budget, choosing rank, alpha, target modules and learning rate, and explain how preference tuning such as DPO differs.

Prerequisites: Transformer Architecture

01. Why it matters

Full fine-tuning updates every weight of a model. To do that, the training loop keeps much more than the weights in GPU memory. With the common mixed-precision setup and the AdamW optimizer, each weight needs its bf16 value (2 bytes), a bf16 gradient (2 bytes), a float32 master copy (4 bytes) and two float32 optimizer statistics (8 bytes): about 16 bytes per weight, before any activations (the intermediate results kept for the backward pass). A 7-billion-weight model therefore needs roughly 100 GiB just for that state, more than a single 24 GB or 80 GB GPU holds.

Parameter-efficient fine-tuning (PEFT) freezes the pretrained weights and trains a small number of new ones. Frozen weights need no gradient and no optimizer state, so memory drops sharply, and the result is a small file that you load on top of the unchanged base model. LoRA is the most widely used PEFT method, and QLoRA combines it with a compressed base model. You need Python 3.12 with torch==2.15.*, transformers==5.23.* and peft==0.21.*; the scripts run on a CPU in seconds, apart from the PEFT one, which loads a 135M-weight model (about 270 MB, downloaded on first use).

Terminal
mkdir -p lora-concepts && cd lora-concepts
python3.12 -m venv .venv
source .venv/bin/activate      # Windows: .venv\Scripts\activate
python -m pip install "torch==2.15.*" --index-url https://download.pytorch.org/whl/cpu
python -m pip install "transformers==5.23.*" "peft==0.21.*"

02. How a LoRA adapter works

A linear layer computes y = W x, where W has d_out × d_in weights. Fine-tuning changes it to W + ΔW. The LoRA paper (Hu et al., 2021) observed that useful updates for a new task can be approximated by a matrix of low rank r: the product of a d_out × r matrix B and an r × d_in matrix A. The layer becomes y = W x + (alpha / r) · B A x. W stays frozen; only A and B are trained. For a 512 × 512 layer and r = 8, that is 2 × 8 × 512 = 8,192 trainable weights instead of 262,144.

Initialisation matters. A starts with small random values and B starts at zero, so B A is zero and the adapted model behaves exactly like the base model at step 0. Training then moves the update away from zero only as far as the data asks. The script writes such a layer by hand, takes one optimizer step and checks what changed. At the end it merges the adapter: it adds scale · B A into a copy of W, which gives a plain linear layer with the same output and no extra cost at inference.

Python · lora_from_scratch.py
"""A LoRA layer written by hand: frozen W plus a trainable low-rank update B @ A."""
import torch
from torch import nn

torch.manual_seed(0)


class LoRALinear(nn.Module):
    def __init__(self, base: nn.Linear, r=8, alpha=16):
        super().__init__()
        self.base = base
        self.base.weight.requires_grad_(False)        # the pretrained weight is frozen
        self.base.bias.requires_grad_(False)
        self.A = nn.Parameter(torch.randn(r, base.in_features) * 0.01)   # random
        self.B = nn.Parameter(torch.zeros(base.out_features, r))         # zeros
        self.scale = alpha / r

    def forward(self, x):
        return self.base(x) + self.scale * (x @ self.A.T @ self.B.T)


base = nn.Linear(512, 512)
layer = LoRALinear(base, r=8, alpha=16)
x = torch.randn(4, 512)
frozen = sum(p.numel() for p in layer.parameters() if not p.requires_grad)
trainable = sum(p.numel() for p in layer.parameters() if p.requires_grad)
print(f"frozen {frozen:,}  trainable {trainable:,}  ({trainable / frozen:.1%})")
print("same output as the base layer at start:", torch.equal(layer(x), base(x)))

w_before = base.weight.clone()
opt = torch.optim.AdamW([layer.A, layer.B], lr=1e-2)
loss = layer(x).pow(2).mean()          # any loss will do for one step
loss.backward()
opt.step()
print("after one step, base weight unchanged:", torch.equal(w_before, base.weight))
print("after one step, B is no longer zero:", bool((layer.B != 0).any()))

merged = nn.Linear(512, 512)
with torch.no_grad():
    merged.weight.copy_(base.weight + layer.scale * layer.B @ layer.A)
    merged.bias.copy_(base.bias)
same = torch.allclose(merged(x), layer(x), atol=1e-5)
print("merged layer gives the same output (within 1e-5):", same)
Terminal
python lora_from_scratch.py
Expected output
frozen 262,656  trainable 8,192  (3.1%)
same output as the base layer at start: True
after one step, base weight unchanged: True
after one step, B is no longer zero: True
merged layer gives the same output (within 1e-5): True

The first step changes B even though it started at zero: its gradient depends on A x, which is not zero. The base weight is untouched, which is what makes the adapter cheap to store and easy to remove. The 3.1% here is for one square layer; for a whole model the share depends on which layers get adapters and on their shapes, as the next script shows.

03. Choosing rank, alpha, target modules and learning rate

The PEFT library adds adapters to an existing Hugging Face model from a LoraConfig. Its main settings are the four you choose for every run:

  • r, the rank: the capacity of the update. Values from 8 to 64 are common. A narrow task such as fixed-format extraction often works at a low rank; a broad change of behaviour may need more.
  • lora_alpha: with scale = alpha / r, it sets how strongly the update is added. Raising r while keeping alpha fixed makes the scale smaller, so each unit of update counts for less; many recipes therefore set alpha to r or 2r. PEFT also offers use_rslora=True, which scales by alpha / sqrt(r), so that the scale falls more slowly as r grows.
  • target_modules: which linear layers get adapters. Attention projections only (q_proj, v_proj…) is the original setup; "all-linear" also covers the feed-forward (MLP) projections, which often improves quality at the cost of more trainable weights.
  • The learning rate: adapters are small and start at zero, so they are usually trained with higher rates than full fine-tuning. Around 1e-4 to 2e-4 is a common starting point for LoRA, compared with around 1e-5 for full tuning; confirm on your validation loss.

The script counts trainable weights for five configurations of SmolLM2-135M-Instruct, the model used in the labs.

Python · peft_counts.py
"""How many weights does LoRA train? Count them for a real model with PEFT."""
import warnings

import torch
from peft import LoraConfig, get_peft_model
from transformers import AutoModelForCausalLM
from transformers.utils import logging

logging.disable_progress_bar()
warnings.filterwarnings("ignore", category=FutureWarning)   # library deprecation notes
MODEL = "HuggingFaceTB/SmolLM2-135M-Instruct"
ATTENTION = ["q_proj", "k_proj", "v_proj", "o_proj"]

base = AutoModelForCausalLM.from_pretrained(MODEL, dtype=torch.float32)
total = sum(p.numel() for p in base.parameters())
layer = base.model.layers[0]
print(f"model: {total / 1e6:.1f}M weights, {len(base.model.layers)} blocks")
print("q_proj", tuple(layer.self_attn.q_proj.weight.shape),
      " k_proj", tuple(layer.self_attn.k_proj.weight.shape),
      " up_proj", tuple(layer.mlp.up_proj.weight.shape))

for targets, r in [(["q_proj", "v_proj"], 8), (ATTENTION, 8),
                   ("all-linear", 8), ("all-linear", 16), ("all-linear", 64)]:
    model = AutoModelForCausalLM.from_pretrained(MODEL, dtype=torch.float32)
    config = LoraConfig(r=r, lora_alpha=2 * r, target_modules=targets,
                        task_type="CAUSAL_LM")
    peft_model = get_peft_model(model, config)
    trainable = sum(p.numel() for p in peft_model.parameters() if p.requires_grad)
    name = targets if isinstance(targets, str) else "+".join(t[0] for t in targets)
    print(f"r={r:<3} {name:11} trainable {trainable:>10,} ({trainable / total:.2%})")
Terminal
python peft_counts.py
Expected output
model: 134.5M weights, 30 blocks
q_proj (576, 576)  k_proj (192, 576)  up_proj (1536, 576)
r=8   q+v         trainable    460,800 (0.34%)
r=8   q+k+v+o     trainable    921,600 (0.69%)
r=8   all-linear  trainable  2,442,240 (1.82%)
r=16  all-linear  trainable  4,884,480 (3.63%)
r=64  all-linear  trainable 19,537,920 (14.52%)

Three things stand out. Adding k_proj and o_proj doubles the count from q+v, as expected. Moving to all linear layers adds the MLP projections, which are larger (up_proj maps 576 to 1,536 values), so the count grows by more than the number of extra layers. And trainable weights grow linearly with r: rank 64 trains eight times as many as rank 8. This small model has a narrow hidden size of 576, so the shares look high; for a 7B model the same rank-16, all-linear setup trains well under 1% of the weights.

04. QLoRA: a 4-bit frozen base

With LoRA the frozen base still sits in memory at 2 bytes per weight in bf16. QLoRA (Dettmers et al., 2023) stores the frozen base in 4 bits instead, using a data type called NF4 (4-bit NormalFloat) designed for weights that are roughly normally distributed. During the forward and backward pass each block of weights is dequantised (converted back) to bf16 on the fly; the adapters themselves are trained in bf16 or float32. Two further tricks save memory: double quantisation also compresses the scaling constants of each block, and paged optimizers move optimizer state to CPU memory when the GPU runs short. In code you pass a BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_use_double_quant=True, bnb_4bit_compute_dtype=torch.bfloat16) when loading the model, which needs a supported GPU and the bitsandbytes package; the CPU labs in this skill use plain LoRA.

The script below turns the bytes-per-weight rules into a table. It is a planning estimate, not a measurement: it leaves out activations, which grow with batch size and sequence length and can be reduced with gradient checkpointing, and it assumes the adapter adds 0.5% of the weights.

Python · memory.py
"""Rough GPU memory for weights, gradients and AdamW state, without activations."""
GIB = 2**30
ADAPTER_SHARE = 0.005   # assumption: LoRA r=16 on all linear layers adds about 0.5%


def full(n):
    # bf16 weights (2) + bf16 grads (2) + fp32 master copy (4) + AdamW m and v (8)
    return n * 16


def lora(n):
    a = n * ADAPTER_SHARE
    return n * 2 + a * 16                  # frozen bf16 base + fully trained adapter


def qlora(n):
    a = n * ADAPTER_SHARE
    return n * 0.5 + n * 0.127 / 8 + a * 16   # 4-bit base + quantisation constants


print(f"{'model':>5} {'full':>8} {'LoRA':>8} {'QLoRA':>8}   (GiB, before activations)")
for billions in (1, 3, 7, 13):
    n = billions * 1e9
    sizes = [full(n) / GIB, lora(n) / GIB, qlora(n) / GIB]
    print(f"{billions:>4}B" + "".join(f" {size:8.1f}" for size in sizes))
Terminal
python memory.py
Expected output
model     full     LoRA    QLoRA   (GiB, before activations)
   1B     14.9      1.9      0.6
   3B     44.7      5.8      1.7
   7B    104.3     13.6      3.9
  13B    193.7     25.2      7.2

Read the table against a 24 GB GPU. Full fine-tuning of even a 1B model leaves little room for activations. LoRA fits a 7B model with about 8 GiB left for activations (24 GB is about 22 GiB). QLoRA fits a 13B model. The price of QLoRA is extra compute for dequantisation, which usually makes each step slower, and a less precise base, although the QLoRA paper reports results that match 16-bit LoRA on its benchmarks. Whatever the method, measure the real peak memory of a short run before you plan a long one.

05. Preference tuning: how DPO differs from SFT

Supervised fine-tuning (SFT) shows the model one good answer per prompt and raises its probability. Preference tuning learns from comparisons instead: for each prompt there is a chosen answer and a rejected one, for example two replies that a reviewer ranked. The older recipe, RLHF with PPO, first trains a separate reward model on such pairs and then optimises the policy against it with reinforcement learning. DPO (Direct Preference Optimization, Rafailov et al., 2023) skips both: it uses the pairs directly in a simple loss.

DPO keeps a frozen copy of the starting model, the reference. For each answer it computes a log-ratio: how much more likely the policy makes it than the reference does. The loss is -log σ(β · (ratio_chosen − ratio_rejected)), where σ is the sigmoid and β controls how far the policy may move from the reference. The script evaluates it on made-up log-probabilities.

Python · dpo_loss.py
"""The DPO loss for one preference pair, computed from sequence log-probabilities."""
import math


def dpo_loss(pol_chosen, pol_rejected, ref_chosen, ref_rejected, beta=0.1):
    # How much more the policy likes each answer than the frozen reference does.
    chosen_ratio = pol_chosen - ref_chosen
    rejected_ratio = pol_rejected - ref_rejected
    margin = beta * (chosen_ratio - rejected_ratio)
    return -math.log(1 / (1 + math.exp(-margin))), margin


# Summed log-probabilities of a chosen and a rejected answer to the same prompt.
ref = {"chosen": -42.0, "rejected": -40.0}   # the reference prefers "rejected" a bit
cases = {
    "policy = reference": (-42.0, -40.0),
    "chosen up by 5": (-37.0, -40.0),
    "rejected down by 5": (-42.0, -45.0),
    "both up by 5": (-37.0, -35.0),
}
for name, (chosen, rejected) in cases.items():
    loss, margin = dpo_loss(chosen, rejected, ref["chosen"], ref["rejected"])
    print(f"{name:20} margin {margin:+.2f}  loss {loss:.3f}")

loss, _ = dpo_loss(-37.0, -40.0, ref["chosen"], ref["rejected"], beta=0.5)
print(f"{'chosen up, beta 0.5':20} loss {loss:.3f}")
Terminal
python dpo_loss.py
Expected output
policy = reference   margin +0.00  loss 0.693
chosen up by 5       margin +0.50  loss 0.474
rejected down by 5   margin +0.50  loss 0.474
both up by 5         margin +0.00  loss 0.693
chosen up, beta 0.5  loss 0.079

When the policy equals the reference, the margin is zero and the loss is log 2 ≈ 0.693. Raising the chosen answer or lowering the rejected one reduces the loss by the same amount, because only the difference between the two log-ratios matters. A larger β makes the same shift count for more. In practice SFT usually comes first, to teach the task and format, and DPO follows to adjust preferences such as tone or which of two valid answers to give. TRL provides a DPOTrainer that takes prompt, chosen and rejected columns, and with a LoRA adapter the base model with the adapter switched off can serve as the reference.

06. Check your understanding

Practice check · 3 questions

LoRA, QLoRA and DPO

Use the scripts and outputs of this lesson.

Q1. In `lora_from_scratch.py` the adapted layer gives exactly the base output before training. Which line makes that true?
Q2. In the `peft_counts.py` output, moving from `q+k+v+o` to `all-linear` at r = 8 raises trainable weights from 921,600 to 2,442,240. Why so much?
Q3. In `dpo_loss.py`, the policy raises the log-probability of both the chosen and the rejected answer by 5 compared with the reference. What happens to the loss, and why?
Practice only: not graded, not saved, not evidence.

07. Apply it

Before you start the QLoRA run of your project (a 1–4B instruct model for JSON extraction), write down its budget. Count the trainable weights of your planned LoraConfig with the code from peft_counts.py, estimate memory with memory.py for your model size and GPU, and decide which of rank, target modules and sequence length you would cut first if a short test run runs out of memory. Record the learning rate you start from and the validation signal you will use to change it. If your project later needs preference data, note how you would collect chosen and rejected pairs for it.

08. Review prompt

Without looking back, answer in your own words:

  1. Why does full fine-tuning need about 16 bytes per weight, and which of those bytes disappear for frozen weights?
  2. Write the LoRA layer equation and explain why B starts at zero.
  3. What does changing r with alpha fixed do to the update, and why might you target all linear layers?
  4. What does QLoRA store in 4 bits, and what does it cost?
  5. What data does DPO need, what is the reference model for, and how does that differ from SFT?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check