TExcelTAD
Home › Math for Deep Learning & LLMs › LoRA and Low-Rank Adaptation

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 ΔW=BA\Delta W = BA for selected matrices. With rank r=8r = 8 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 W0∈Rm×nW_0 \in \mathbb{R}^{m \times n}, LoRA computes

h=W0x+αrBAx,B∈Rm×r,A∈Rr×n,r≪min⁡(m,n)\mathbf{h} = W_0\mathbf{x} + \frac{\alpha}{r}BA\mathbf{x}, \qquad B \in \mathbb{R}^{m \times r}, \quad A \in \mathbb{R}^{r \times n}, \quad r \ll \min(m, n)

rank⁡(BA)≤r\operatorname{rank}(BA) \le r. AA is initialized randomly and BB to zero, so training starts exactly at the pre-trained model. The scale α/r\alpha/r keeps the effective learning rate roughly independent of the rank. Trainable parameters: r(m+n)r(m + n) instead of mnmn.

python · try it yourself
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-rr approximation captures most of the update (by the Eckart-Young theorem, the truncated SVD is the best rank-rr approximation).

python · try it yourself
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 4⋅128=5124 \cdot 128 = 512 trainable numbers instead of 4096.

Merging and serving

After training, W=W0+αrBAW = W_0 + \frac{\alpha}{r}BA 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 W0W_0 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 WQW_Q and WVW_V 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", ...]), then get_peft_model(model, config); merge_and_unload() merges.
  • Only AA and BB 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. 10−410^{-4} instead of 10−510^{-5}).

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 4096×40964096 \times 4096 attention matrices in each of 32 layers. How many trainable parameters?

Answer

16,777,216.

Solution

Per matrix 16⋅(4096+4096)=131,07216 \cdot (4096 + 4096) = 131{,}072; times 4⋅32=1284 \cdot 32 = 128 matrices gives 16,777,21616{,}777{,}216, about 0.25% of a 7B model.

Exercise 2: Why initialize B to zero?

What would go wrong if both AA and BB were random at the start?

Answer

The model would start from a randomly perturbed version of the pre-trained model.

Solution

With B=0B = 0, BA=0BA = 0 and the network output is exactly the pre-trained one at step 0. Random BB would add noise to every adapted layer before any learning, damaging the knowledge fine-tuning is meant to keep. (AA must not also be zero, or both gradients would be zero.)

Exercise 3: Rank of the update (code)

Show that BABA with B∈R100×8B \in \mathbb{R}^{100 \times 8} and A∈R8×100A \in \mathbb{R}^{8 \times 100} has rank 8 (for random entries).

Answer

matrix_rank returns 8.

Solution
python · try it yourself
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…

  1. all weights of the model
  2. a low-rank update BABA added to frozen weights
  3. only the biases
  4. a new tokenizer

How many trainable parameters does rank-rr LoRA add to an m×nm \times n matrix?

  1. mnmn
  2. r(m+n)r(m + n)
  3. r2r^2
  4. m+nm + n

Why does a merged LoRA model have no extra inference cost?

  1. Adapters are deleted
  2. W0+αrBAW_0 + \frac{\alpha}{r}BA is a single matrix of the original shape
  3. Inference skips those layers
  4. It runs on the CPU