Learn the MachineDansk

Explained with an interactive demo

What is LoRA?

LoRA (low-rank adaptation) is a widely used way to adapt a large language model without training all its weights. The model is frozen, and next to chosen weight matrices you train two small matrices whose product is the change. Try it on a network in your browser and see when a low rank is enough and when it is not. Below the demo: a parameter calculator for real models, what r and alpha do, and LoRA in about 30 lines of PyTorch.

The demo needs JavaScript. The text below explains what it shows.

Embed this demo on your site

Copy the code into your page. The demo loads from learnthemachine.com, so it stays up to date, and the link under it shows where it comes from.

The problem with training everything

Full fine-tuning updates every single weight. For Llama 2 7B that is 6.74 billion numbers, and during training with Adam a gradient and two optimiser states have to be stored for each of them on top of the weights. Afterwards you have a new copy of the whole model, 13.5 GB at 16 bits, for every task you adapted it to.

The idea: learn the change as a product of two small matrices

LoRA freezes the pretrained weight matrix W and instead learns a change ΔW = B · A, where B has d × r numbers and A has r × d numbers. The rank r is small, often between 4 and 64, while d is in the hundreds or thousands. The layer computes W · x + B · (A · x), so a full ΔW never has to be formed during training. A product of a d × r and an r × d matrix has rank at most r: all its rows are combinations of the same r rows of A.

A starts with small random numbers and B with zeros, so B · A = 0 at the first step and the model behaves exactly as it did before training. You can see this in the demo, where ΔW starts blank. Most implementations also multiply the change by a factor α/r; in the demo it is 1.

When is a low rank enough?

Hu et al. (2021), who introduced LoRA, hypothesised that the change a model needs during adaptation has a low “intrinsic rank”. In their experiments with GPT-3 175B, rank 1 and 2 on the query and value matrices did almost as well as higher ranks on the two tasks they measured it on. The demo shows both sides. When one cluster has to change class, rank 1 with 64 trainable numbers is enough to get all 60 test points right. When every class swaps, rank 1 reaches only 87%, rank 2 93%, rank 4 95%, rank 8 97% and the whole layer, with 1,056 trainable numbers, 98%. The bigger the change, the more rank it needs.

No extra latency

After training, B · A can be added straight into the weight: W′ = W + B · A has the same shape as W, so the adapted model is exactly as fast as the original. You can also keep the adapters separate and switch between them, so one base model can serve many tasks, each with its own adapter of a few megabytes. Hu et al. report that for GPT-3 175B, LoRA reduced the number of trainable parameters by about 10,000 times and GPU memory by about 3 times compared with full fine-tuning with Adam.

Where do the adapters go?

The original paper adapted only the query and value matrices in the attention layers. With QLoRA, Dettmers et al. (2023) found that adapters on all linear layers were needed to match full fine-tuning, and combined them with a base model quantised to 4 bits. That made it possible to fine-tune a 65-billion-parameter model on a single GPU with 48 GB of memory. The calculator above shows what the choices cost in numbers: for Llama 2 7B, rank 8 on q and v gives 4,194,304 trainable numbers, 0.06% of the model.

The settings: r, alpha, dropout and target modules

Four settings decide what a LoRA adapter can learn. The names are the ones the Hugging Face PEFT library uses.

LoRA in PyTorch

A LoRA layer is a wrapper around an existing nn.Linear. The code below needs only PyTorch, and each print is followed by what it prints. The sizes are those of one attention matrix in Llama 2 7B, 4,096 × 4,096.

import math
import torch
from torch import nn


class LoRALinear(nn.Module):
    """A frozen nn.Linear plus a trainable low-rank change (alpha / r) * B @ A."""

    def __init__(self, base, r=8, alpha=16, dropout=0.0):
        super().__init__()
        self.base = base
        for p in self.base.parameters():
            p.requires_grad = False  # W stays frozen
        self.A = nn.Parameter(torch.empty(r, base.in_features))
        self.B = nn.Parameter(torch.zeros(base.out_features, r))  # B = 0, so the change starts at 0
        nn.init.kaiming_uniform_(self.A, a=math.sqrt(5))  # the same start as nn.Linear's weights
        self.scale = alpha / r
        self.dropout = nn.Dropout(dropout)

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

    @torch.no_grad()
    def merge(self):
        """Fold the change into W: a plain nn.Linear, as fast as the original."""
        merged = nn.Linear(self.base.in_features, self.base.out_features,
                           bias=self.base.bias is not None)
        merged.weight.copy_(self.base.weight + self.scale * self.B @ self.A)
        if self.base.bias is not None:
            merged.bias.copy_(self.base.bias)
        return merged


torch.manual_seed(0)
layer = LoRALinear(nn.Linear(4096, 4096, bias=False), r=8, alpha=16)
trainable = sum(p.numel() for p in layer.parameters() if p.requires_grad)
frozen = sum(p.numel() for p in layer.parameters() if not p.requires_grad)
print(trainable, frozen)
# 65536 16777216

x = torch.randn(4, 4096)
print(torch.equal(layer(x), layer.base(x)))  # B = 0: the same output as before
# True

opt = torch.optim.AdamW([p for p in layer.parameters() if p.requires_grad], lr=1e-3)
loss = (layer(x) - torch.randn(4, 4096)).pow(2).mean()  # one step towards a made-up target
loss.backward()
opt.step()
print(layer.base.weight.grad is None, layer.B.abs().max().item() > 0)  # W got no gradient, B moved
# True True

merged = layer.merge()
print(torch.allclose(merged(x), layer(x), atol=1e-5))
# True

The adapter has 65,536 trainable numbers next to 16,777,216 frozen ones, 0.39% of the matrix: 8 × (4,096 + 4,096). Before training, its output is exactly that of the original layer, because B starts as zeros. After training, merge() returns a plain layer with the change folded in, so inference costs nothing extra.

In practice you rarely write this yourself. With PEFT, the same adapter on q and v in every layer of a model looks like this:

from peft import LoraConfig, get_peft_model
from transformers import AutoModelForCausalLM

model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B")
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(model, config)  # freezes the model and adds A and B
model.print_trainable_parameters()  # trainable params: 540,672 ...

# ... train as usual, then:
model = model.merge_and_unload()  # W + (alpha / r) * B @ A, a plain model again

For Qwen2.5-0.5B that is 540,672 trainable numbers, about 0.11% of the model: each of the 24 layers gets 8 × (896 + 896) for q and 8 × (896 + 128) for v, because the model has only two key/value heads of 64 dimensions. The calculator above gives the same numbers.

Limits

LoRA is a trade-off, not a free shortcut. Biderman et al. (2024) compared LoRA with full fine-tuning on programming and maths and found that LoRA generally learned less of the new domain but also forgot less of what the model could already do. The rank, which layers to adapt and the learning rate have to be chosen by measuring, and an adapter that works on the training examples still has to be tested on new ones. The demo is a small network on synthetic points; the numbers show the idea, not what happens in a particular language model.

Train an adapter on a real language model

In the Open language model lab you train a small low-rank adapter on the output layer of Pythia-70M on your own computer. The model’s 70.4 million weights are frozen; at rank 4, 203,264 numbers are trained. You compare the training examples with validation prompts that are not used for gradients, and can repeat the experiment with three seeds. The lab requires full access.

See the Open language model labOr watch a model learn with gradient descent, free

More explainers