LoRA: Low-Rank Adaptation from Scratch
Full fine-tuning changes every weight of a model, so each task needs its own full copy and the optimiser keeps two extra numbers per weight. LoRA (low-rank adaptation, Hu et al., 2021) freezes the pretrained weights and learns only a small correction for some of the matrices, written as the product of two thin matrices. For a 4096 x 4096 attention projection, a rank-8 correction has 65,536 trainable numbers instead of 16.8 million. This lesson builds LoRA in NumPy, gradients included, and checks the claim it rests on: the change a task needs is often low-rank.
The idea in one picture
The input goes through the frozen weight as before, and also through a narrow side path: squeezes it to numbers, expands it back. The two results are added. Because starts at zero, the side path adds nothing at first and the layer is exactly the pretrained one.
Definitions
For a frozen weight (the layer computes ), LoRA learns
- has rank at most (a product through an -dimensional bottleneck, see Low-Rank Approximation).
- Trainable parameters: instead of .
- Initialisation: random (Gaussian or Kaiming-uniform), , so at step 0. (Both zero would be a dead end: every gradient would be zero.)
- Scale : is a fixed hyperparameter (often or ). With the scale, changing does not change the size of the update much, so a learning rate tuned for one rank roughly works for another.
- Merging: after training, is one ordinary matrix. The merged model has the same size and speed as the original: no extra inference cost, unlike adapters.
The gradients
LoRA needs no new calculus. If is the gradient the frozen weight would get, the chain rule through with gives
At step 0, , so and only moves; from step 1 on both learn. The derivation and the parameter counts for real LLM layers are in LoRA and Low-Rank Adaptation.
From scratch: is the needed change low-rank?
A controlled experiment first. A "pretrained" linear layer (64 x 64) is frozen. The new task needs , where the change has rank 2 by construction. We get 120 noisy training pairs and fit LoRA of rank 1, 2, 4 and 8 with Adam, and, for comparison, full fine-tuning (the least-squares fit of all 4,096 weights). The test error is measured on 2,000 new inputs against the noise-free targets.
import numpy as np
rng = np.random.default_rng(0)
d, n = 64, 120
W0 = rng.normal(0, 1 / np.sqrt(d), (d, d)) # pretrained weight: frozen
dW_true = 0.5 * rng.normal(size=(d, 2)) @ rng.normal(size=(2, d)) / np.sqrt(d) # the task needs a rank-2 change
W_star = W0 + dW_true
X_tr, X_te = rng.normal(size=(n, d)), rng.normal(size=(2000, d))
Y_tr = X_tr @ W_star.T + 0.5 * rng.normal(size=(n, d)) # noisy targets; each row is h = W x
Y_te = X_te @ W_star.T # noise-free targets for the test
def test_mse(W):
return np.mean((X_te @ W.T - Y_te) ** 2)
def lora_fit(r, alpha=8, steps=1500, lr=0.01):
A = rng.normal(0, 1 / np.sqrt(d), (r, d)) # A random, B zero: training starts at W0
B = np.zeros((d, r))
s = alpha / r
mA = vA = mB = vB = 0
for t in range(1, steps + 1):
E = X_tr @ (W0 + s * B @ A).T - Y_tr # residuals, n x d
G = E.T @ X_tr / n # dL/dW of the squared error / 2
gB, gA = s * G @ A.T, s * B.T @ G # chain rule through W = W0 + s B A
mB = 0.9 * mB + 0.1 * gB; vB = 0.999 * vB + 0.001 * gB ** 2 # Adam
mA = 0.9 * mA + 0.1 * gA; vA = 0.999 * vA + 0.001 * gA ** 2
c = np.sqrt(1 - 0.999 ** t) / (1 - 0.9 ** t)
B -= lr * c * mB / (np.sqrt(vB) + 1e-8)
A -= lr * c * mA / (np.sqrt(vA) + 1e-8)
return W0 + s * B @ A
print(f"frozen W0 trainable {0:5d} test MSE {test_mse(W0):.4f}")
fits = {}
for r in [1, 2, 4, 8]:
fits[r] = lora_fit(r)
print(f"LoRA r = {r} trainable {2 * d * r:5d} test MSE {test_mse(fits[r]):.4f}")
W_full = np.linalg.lstsq(X_tr, Y_tr, rcond=None)[0].T # full fine-tuning: all d*d weights
print(f"full fine-tuning trainable {d * d:5d} test MSE {test_mse(W_full):.4f}")
print("singular values of the r = 8 update:", np.linalg.svd(fits[8] - W0, compute_uv=False)[:8].round(2))
print("singular values of the true change: ", np.linalg.svd(dW_true, compute_uv=False)[:3].round(2))frozen W0 trainable 0 test MSE 0.5475
LoRA r = 1 trainable 128 test MSE 0.1908
LoRA r = 2 trainable 256 test MSE 0.0113
LoRA r = 4 trainable 512 test MSE 0.0455
LoRA r = 8 trainable 1024 test MSE 0.1086
full fine-tuning trainable 4096 test MSE 0.3099
singular values of the r = 8 update: [4.87 3.51 1.35 1.19 0.96 0.93 0.77 0.68]
singular values of the true change: [4.86 3.43 0. ]
Without any training the frozen layer has a test error of 0.5475. Rank 1 cannot express a rank-2 change and stops at 0.1908. Rank 2 matches the true change and gets the error down to 0.0113 with 256 trainable numbers. Higher ranks get worse (0.0455 at , 0.1086 at ), and full fine-tuning, with all 4,096 weights free, is worst of the fitted models at 0.3099: the extra freedom is spent on fitting the noise of 120 examples. The singular values tell the same story: the rank-8 update found the two real directions (4.87 and 3.51 against the true 4.86 and 3.43) and spread smaller values (1.35 and below) over six directions that are pure noise.
This is the LoRA hypothesis in miniature. When the change a task needs has low intrinsic rank, restricting the update to that rank is not a compromise but a regulariser. Real fine-tuning updates are not exactly low-rank, but their singular values decay fast, which is why ranks 4 to 16 work for models with matrices of size 4096.
LoRA inside a network
Now a real (if small) network: the digit classifier of the earlier lessons. An MLP with one hidden layer of 64 ReLU units is pretrained on one half of the 8 x 8 digits. The target is the other half photographed by a camera shifted one pixel to the right: the same ten digits, but every pixel has moved, so the pretrained first layer looks in slightly wrong places. 30 labelled images per class (300) train each method and the other 599 images test it, averaged over 3 draws of the labelled images. Every method trains a new 10-class head; LoRA adds a rank- update to the 64 x 64 first layer.
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier
X, y = load_digits(return_X_y=True)
X = X / 16.0
X_src, X_tgt, y_src, y_tgt = train_test_split(X, y, test_size=0.5, random_state=0, stratify=y)
source = MLPClassifier(hidden_layer_sizes=(64,), max_iter=500, random_state=0).fit(X_src, y_src)
W0, b0 = source.coefs_[0], source.intercepts_[0] # pretrained first layer (64 in, 64 out), frozen
X_new = np.roll(X_tgt.reshape(-1, 8, 8), 1, axis=2).reshape(-1, 64) # target images: shifted 1 pixel right
print(f"pretrained model, no training: unshifted target images {source.score(X_tgt, y_tgt):.3f}, shifted {source.score(X_new, y_tgt):.3f}")
def forward(P, A_in, s):
W = P["W"] if "W" in P else W0
if "A" in P:
W = W + s * P["A"] @ P["B"] # rows are inputs here: h = x W, so dW = s A B
pre = A_in @ W + b0
h = np.maximum(0, pre)
return pre, h, h @ P["V"] + P["c"]
def train(P, Xl, yl, s=1.0, lr=0.003, steps=300):
m = {k: 0 for k in P}; v = {k: 0 for k in P}
for t in range(1, steps + 1):
pre, h, z = forward(P, Xl, s)
p = np.exp(z - z.max(1, keepdims=True)); p /= p.sum(1, keepdims=True)
g = p.copy(); g[np.arange(len(yl)), yl] -= 1; g /= len(yl)
G = {"V": h.T @ g, "c": g.sum(0)}
GW = Xl.T @ ((g @ P["V"].T) * (pre > 0)) # gradient for the whole first-layer matrix
if "W" in P: G["W"] = GW
if "A" in P: G["A"], G["B"] = s * GW @ P["B"].T, s * P["A"].T @ GW
for k in P: # Adam
m[k] = 0.9 * m[k] + 0.1 * G[k]; v[k] = 0.999 * v[k] + 0.001 * G[k] ** 2
P[k] = P[k] - lr * (m[k] / (1 - 0.9 ** t)) / (np.sqrt(v[k] / (1 - 0.999 ** t)) + 1e-8)
return P
def new_params(method, r, rng):
P = {"V": rng.normal(0, 0.1, (64, 10)), "c": np.zeros(10)} # new head
if method == "full":
P["W"] = W0.copy()
if method == "lora":
P["A"], P["B"] = rng.normal(0, 1 / np.sqrt(64), (64, r)), np.zeros((r, 64))
return P
print("method trainable test accuracy (599 images, mean of 3 draws)")
for method, r in [("head only", 0), ("lora", 1), ("lora", 4), ("lora", 8), ("lora", 16), ("full", 0)]:
accs = []
for seed in range(3):
rng = np.random.default_rng(seed)
lab = np.concatenate([rng.choice(np.where(y_tgt == c)[0], 30, replace=False) for c in range(10)])
test = np.setdiff1d(np.arange(len(y_tgt)), lab)
P = train(new_params(method, r, rng), X_new[lab], y_tgt[lab], s=8 / max(r, 1))
accs.append((forward(P, X_new[test], 8 / max(r, 1))[2].argmax(1) == y_tgt[test]).mean())
n_train = sum(p.size for p in new_params(method, r, rng).values())
name = f"LoRA r = {r}" if method == "lora" else method
print(f"{name:13s} {n_train:9d} {np.mean(accs):.3f}")
# merging: the trained update folds into one ordinary matrix
s = 8 / 4
P = train(new_params("lora", 4, np.random.default_rng(0)), X_new[lab], y_tgt[lab], s=s)
W_merged = W0 + s * P["A"] @ P["B"]
z_lora = forward(P, X_new[test], s)[2]
z_merged = np.maximum(0, X_new[test] @ W_merged + b0) @ P["V"] + P["c"]
print("merged model gives the same logits:", bool(np.abs(z_lora - z_merged).max() < 1e-9))pretrained model, no training: unshifted target images 0.971, shifted 0.466
method trainable test accuracy (599 images, mean of 3 draws)
head only 650 0.899
LoRA r = 1 778 0.896
LoRA r = 4 1162 0.925
LoRA r = 8 1674 0.935
LoRA r = 16 2698 0.937
full 4746 0.940
merged model gives the same logits: True
Without training, the pretrained network gets only 0.466 on the shifted images: a one-pixel move breaks a model that scored 0.971 on the unshifted ones, because an MLP's first layer is tied to pixel positions. A new head on the frozen layer recovers 0.899. Adding LoRA to the first layer climbs with the rank: 0.896 at (no better than the head alone), 0.925 at , 0.935 at and 0.937 at , close to full fine-tuning's 0.940 with 2,698 instead of 4,746 trainable numbers. (Here the counts include the 650 numbers of the new head; the first layer alone has 4,096 weights against 128 per rank for LoRA.) Each test score is 599 images, so 0.002 is about one image: ranks 8 and 16 and full fine-tuning are within three images of each other.
The last line checks merging: (the row convention of scikit-learn, , transposes the formula) used as an ordinary weight matrix gives the same logits as the frozen weight plus the side path.
The savings are modest on a 64 x 64 layer. They grow with the size of the matrix, because LoRA's cost is linear in and full fine-tuning's is quadratic: for a 4096 x 4096 projection, is 0.4 % of the weights. The next lesson does the same on a pretrained transformer with Hugging Face PEFT.
Choosing the rank, and the target matrices
- Rank . 4 to 16 is the usual range for LLM fine-tuning; 1 or 2 often works surprisingly well for narrow tasks, 64 or more for tasks far from pretraining (a new language, code for a model that saw little code). The first experiment shows both failure modes: too small a rank cannot express the change (bias), too large a rank fits noise (variance) and drifts towards full fine-tuning.
- . With the scale, keep fixed while trying ranks. A common default is for the rank you settle on. A variant, rsLoRA, scales by so that large ranks still learn.
- Which matrices. The original paper adapted only the attention query and value projections; adapting all linear layers (query, key, value, output, and the MLP) usually helps more than raising the rank, for the same parameter budget.
- Learning rate. LoRA tolerates and needs a larger learning rate than full fine-tuning: about to with AdamW, against to for full fine-tuning of a transformer.
Advantages and limits
| Advantages | Limits |
|---|---|
| A tiny fraction of the parameters trains: less optimiser memory, faster steps | The frozen weights still have to be stored and run forward and backward: activation memory stays |
| One base model, many small adapters (a few MB each) to switch per task or customer | Can underfit when the task needs a big change (new language or domain) at small rank |
| Merges into : zero inference overhead | A merged model loses the easy switching; unmerged adds a little latency |
| Starts exactly at the pretrained model (), so training is stable | Extra hyperparameters: rank, , target modules |
| The base stays intact, which limits catastrophic forgetting | Forgetting is limited, not abolished: the adapted model can still lose skills |
Pitfalls
- Initialising both and at zero. Then both gradients are zero forever: the side path never learns.
- Initialising at random. Training then starts from a randomly perturbed model, not the pretrained one.
- Comparing ranks with a fixed but a different . Keep constant across a rank sweep, or the comparison also changes the effective learning rate.
- Forgetting the head. For a new classification task the output layer is new and must train in full (in PEFT:
modules_to_save), as in the second example. - Merging into a quantised base. Adding to 4-bit weights requantises them and loses precision; merge into a higher-precision copy (QLoRA).
Practice
- A layer has , . How many parameters does a rank-8 LoRA add, as a percentage of the layer?
- Why is the gradient of zero at the first step, and why is that not a problem?
- In the first experiment, why is the full least-squares fit worse than LoRA with although it can represent exactly?
Answers
- , against : about 1.3 %.
- and . 's gradient is not zero (A is random), so moves at the first step and gets gradients from the second.
- It has 4,096 free numbers and only 120 noisy examples, so it fits the noise as well as the signal (high variance). LoRA with has the right shape for the true change and only 256 numbers; the restriction acts as a strong, correct prior.
Test yourself
Why is B initialised to zero in LoRA?
- To save memory
- So that the update BA is zero and training starts exactly at the pretrained model
- Because B is never trained
- To make the rank zero forever
How many trainable parameters does a rank-r LoRA on a 4096 x 4096 matrix have?
- 4096 r
- 2 x 4096 r
- 4096 squared
- r squared
What does merging a LoRA adapter mean?
- Training A and B together
- Adding (alpha/r) BA into W0 so the model is one ordinary matrix again, with no extra inference cost
- Averaging two adapters
- Quantising the adapter
In the first experiment the true change has rank 2. Why does LoRA with r = 8 do worse than r = 2 on the test set?
- Rank 8 cannot represent a rank-2 change
- The extra directions are fitted to the noise of the 120 training examples
- Adam diverges at rank 8
- alpha / r is undefined for r = 8