LoRA and Low-Rank Adaptation
Fine-tuning every weight of a 7B-parameter model needs the full optimizer state (about 112 GB) and produces a 14 GB copy per task. LoRA (Hu et al., 2021) freezes the pre-trained weights and learns a low-rank update for selected matrices. With rank or 16, it trains well under 1% of the parameters, often matching full fine-tuning on a task, and the update can be merged into the weights for free inference. The linear algebra is the SVD and low-rank approximation.
The update
For a frozen weight , LoRA computes
. is initialized randomly and to zero, so training starts exactly at the pre-trained model. The scale keeps the effective learning rate roughly independent of the rank. Trainable parameters: instead of .
import numpy as np
m = n = 4096
for r in (4, 8, 16, 64):
lora, full = r * (m + n), m * n
print(f"r = {r:3d}: {lora:9,d} trainable vs {full:,d} ({lora / full:.2%})")r = 4: 32,768 trainable vs 16,777,216 (0.20%)
r = 8: 65,536 trainable vs 16,777,216 (0.39%)
r = 16: 131,072 trainable vs 16,777,216 (0.78%)
r = 64: 524,288 trainable vs 16,777,216 (3.12%)
Why low rank is enough
The hypothesis behind LoRA: the change needed to adapt a model to a task has low intrinsic rank, even though the weights themselves are full rank. Empirically, the singular values of full fine-tuning updates decay quickly, so a rank- approximation captures most of the update (by the Eckart-Young theorem, the truncated SVD is the best rank- approximation).
import numpy as np
rng = np.random.default_rng(0)
m, n, r_true = 64, 64, 4
W0 = rng.normal(size=(m, n)) / np.sqrt(n) # frozen pre-trained weight
delta = rng.normal(size=(m, r_true)) @ rng.normal(size=(r_true, n)) / n + 0.002 * rng.normal(size=(m, n))
X = rng.normal(size=(512, n)); Y = X @ (W0 + delta).T # the "task" needs W0 + delta
alpha, r = 8.0, 4
A = rng.normal(0, 1 / np.sqrt(n), (r, n)); B = np.zeros((m, r)) # B = 0: start at W0
lr = 0.01
for step in range(1501):
H = X @ W0.T + (alpha / r) * (X @ A.T) @ B.T
G = 2 * (H - Y) / len(X) # dLoss/dH for mean squared error
gB = (alpha / r) * G.T @ (X @ A.T)
gA = (alpha / r) * (G @ B).T @ X
B -= lr * gB; A -= lr * gA
if step % 500 == 0:
print(f"step {step:4d}: loss {np.mean((H - Y)**2):.6f}")
learned = (alpha / r) * B @ A
print(f"relative error of the learned update: {np.linalg.norm(learned - delta) / np.linalg.norm(delta):.3f}")
s = np.linalg.svd(delta, compute_uv=False)
print("singular values of the true update:", np.round(s[:6], 3))step 0: loss 0.067290
step 500: loss 0.000536
step 1000: loss 0.000230
step 1500: loss 0.000229
relative error of the learned update: 0.059
singular values of the true update: [1.332 1.054 0.847 0.767 0.031 0.029]
The true update is rank 4 plus small noise; a rank-4 LoRA recovers it up to the noise, with trainable numbers instead of 4096.
Merging and serving
After training, is an ordinary matrix: merged LoRA adds no inference cost. Unmerged, one base model can serve many tasks by swapping small adapters (a few MB each) per request.
Variants
- QLoRA: keep the frozen in 4-bit precision and train LoRA adapters in bf16 on top; fine-tuning a 65B model fits on one large GPU.
- DoRA: decompose each weight into magnitude and direction and apply LoRA to the direction.
- Where to apply: originally only and of attention; today usually all linear layers, which gives better quality.
In software
- Hugging Face
peft:LoraConfig(r=16, lora_alpha=32, target_modules=["q_proj", "v_proj", ...]), thenget_peft_model(model, config);merge_and_unload()merges. - Only and need gradients and optimizer state, so memory is dominated by the frozen weights and activations.
- A typical learning rate for LoRA is higher than for full fine-tuning (e.g. instead of ).
Go further: LoRA: Low-Rank Adaptation from Scratch tests whether a needed change is really low-rank and how to choose the rank and targets, and LoRA and QLoRA for LLMs in Practice applies it to language models.
Exercises
Exercise 1: Trainable parameters
A model applies rank-16 LoRA to four attention matrices in each of 32 layers. How many trainable parameters?
Answer
16,777,216.
Solution
Per matrix ; times matrices gives , about 0.25% of a 7B model.
Exercise 2: Why initialize B to zero?
What would go wrong if both and were random at the start?
Answer
The model would start from a randomly perturbed version of the pre-trained model.
Solution
With , and the network output is exactly the pre-trained one at step 0. Random would add noise to every adapted layer before any learning, damaging the knowledge fine-tuning is meant to keep. ( must not also be zero, or both gradients would be zero.)
Exercise 3: Rank of the update (code)
Show that with and has rank 8 (for random entries).
Answer
matrix_rank returns 8.
Solution
import numpy as np
rng = np.random.default_rng(3)
B, A = rng.normal(size=(100, 8)), rng.normal(size=(8, 100))
print(np.linalg.matrix_rank(B @ A), (B @ A).shape)8 (100, 100)
Test yourself
LoRA trains…
- all weights of the model
- a low-rank update added to frozen weights
- only the biases
- a new tokenizer
How many trainable parameters does rank- LoRA add to an matrix?
Why does a merged LoRA model have no extra inference cost?
- Adapters are deleted
- is a single matrix of the original shape
- Inference skips those layers
- It runs on the CPU