Algorithm Search⌘K

Algorithmresearch

Low-rank adaptation

Also called LoRA.

Fine-tune a large model by freezing a weight matrix W0 and training a rank-r update B A, scaled by alpha / r and zero at the start. The update merges into W0, so inference costs nothing extra.

Time
Θ(n (d k + r (d + k))) worst
Space
Θ(r (d + k)) extra
Where
d = the output size of the adapted matrix; k = the input size of the adapted matrix; n = the number of tokens; r = the rank of the update
Properties
deterministicexactofflineiterative
Origin
Edward J. Hu, Yelong Shen, Phillip Wallis, Zeyuan Allen Zhu, Yuanzhi Li, Shean Wang, Lu Wang, Weizhu Chen, 2021

Low-rank adaptation (LoRA) fine-tunes a large pretrained network without changing its weights. For a chosen weight matrix W0W_0 of shape d×kd \times k, it freezes W0W_0 and trains two small matrices BB (d×rd \times r) and AA (r×kr \times k) with a rank rr much smaller than dd and kk. The layer computes h=W0x+(α/r)BAxh = W_0 x + (\alpha / r) B A x. BB starts at zero, so training starts exactly at the pretrained network. After training, (α/r)BA(\alpha / r) B A can be added into W0W_0, so the adapted network runs at the same cost as the original one. LoRA is a way to parametrize fine-tuning: it says which numbers are trained, not what data they are trained on. Instruction tuning, the reward model of RLHF and direct preference optimization are often run with LoRA, and they are separate pages.

In plain words

A large model has big tables of numbers. Changing all of them for every new task needs a lot of memory, and each task gets a full copy of the model.

LoRA keeps the big tables fixed. Next to one table it puts two thin tables. Their product has the same shape as the big table, but it can describe only a few independent directions of change. Only the thin tables learn.

At the start one thin table is all zeros, so the model behaves exactly as before. During training the thin tables learn the change that the task needs.

When training ends, you can add the product of the thin tables into the big table once. The model is then as fast as before. You can also keep the thin tables apart and swap them to change the task.

The problem

The input is a pretrained matrix W0∈Rd×kW_0 \in \mathbb{R}^{d \times k} that maps an input x∈Rkx \in \mathbb{R}^k to W0x∈RdW_0 x \in \mathbb{R}^d, for example the query projection WqW_q of an attention layer, with d=k=dmodeld = k = d_{\text{model}}. Full fine-tuning learns an update Δ\Delta of the same shape, so dkd k new numbers per matrix, plus the optimizer state for each of them. LoRA restricts the update to the form

Δ=sBA,B∈Rd×r,A∈Rr×k,s=αr,r≪min⁡(d,k),\Delta = s B A, \qquad B \in \mathbb{R}^{d \times r}, \quad A \in \mathbb{R}^{r \times k}, \quad s = \frac{\alpha}{r}, \quad r \ll \min(d, k),

so it trains r(d+k)r (d + k) numbers. The hypothesis of Hu and colleagues is that the change that a downstream task needs has a low "intrinsic rank". That is a measured observation on their tasks, not a theorem: Section 7.2 of their paper reports that r=1r = 1 already does well on WikiSQL and MultiNLI for GPT-3 175B when both WqW_q and WvW_v are adapted, and they say that they do not expect a small rr to work for every task. The scale α\alpha is a constant; Hu and colleagues set α\alpha to the first rr they try and do not tune it, so that changing rr later needs less retuning of the learning rate.

For a sequence of nn tokens, XX is n×kn \times k and the output is H=XW0⊤+s(XA⊤)B⊤H = X W_0^\top + s (X A^\top) B^\top, of shape n×dn \times d.

The algorithm

The algorithm has an initialization, a forward pass, a backward pass that gives the gradients of AA and BB (and of the input, for the layers below), and the merge and unmerge steps. W0W_0 is never changed during training. The optimizer (for example AdamW) updates AA and BB with the gradients of lines L6 and L7.

  1. LORA-INIT(d, k, r, σ)
  2. 1A ← r × k matrix with entries drawn from N(0, σ^2)
  3. 2B ← d × r zero matrix
  4. LORA-FORWARD(W0, A, B, α, x) ▷ x: k numbers, s = α / r
  5. 3u ← A x ▷ r numbers
  6. 4return h ← W0 x + s B u ▷ d numbers, B A is never formed
  7. LORA-BACKWARD(W0, A, B, α, x, g) ▷ g = ∂ℓ/∂h: d numbers
  8. 5u ← A x; c ← B^T g ▷ r numbers each
  9. 6∇B ← s g u^T ▷ d × r
  10. 7∇A ← s c x^T ▷ r × k
  11. 8∇x ← W0^T g + s A^T c ▷ k numbers
  12. LORA-MERGE(W0, A, B, α)
  13. 9return W ← W0 + s B A
  14. LORA-UNMERGE(W, A, B, α)
  15. 10return W0 ← W - s B A

For a batch of nn tokens the gradients of AA and BB are the sums of lines L6 and L7 over the tokens.

Example

Take d=2d = 2, k=3k = 3, r=1r = 1 and α=2\alpha = 2, so s=2s = 2, with

W0=(10201−1),A=(120),B=(0.5−1),x=(111).W_0 = \begin{pmatrix} 1 & 0 & 2 \\ 0 & 1 & -1 \end{pmatrix}, \quad A = \begin{pmatrix} 1 & 2 & 0 \end{pmatrix}, \quad B = \begin{pmatrix} 0.5 \\ -1 \end{pmatrix}, \quad x = \begin{pmatrix} 1 \\ 1 \\ 1 \end{pmatrix}.
step value
L3 u=Axu = A x 3
W0xW_0 x (3, 0)
sBus B u (3, -6)
L4 hh (6, -6)
L9 sBAs B A rows (1, 2, 0) and (-2, -4, 0)
L9 WW rows (2, 2, 2) and (-2, -3, -1)
WxW x (6, -6), the same as L4

The update sBAs B A has rank 1, as both of its rows are multiples of AA. With B=0B = 0 (line L2) the same input gives h=W0x=(3,0)h = W_0 x = (3, 0), the pretrained output.

At scale, take GPT-3 175B, which has 96 layers and dmodel=12288d_{\text{model}} = 12288. One 12288×1228812288 \times 12288 matrix has 150,994,944 entries. LoRA with r=4r = 4 on that matrix trains 4×(12288+12288)=98,3044 \times (12288 + 12288) = 98{,}304 numbers. Adapting WqW_q and WvW_v in all 96 layers trains 96×2×r×2457696 \times 2 \times r \times 24576 numbers: 4,718,592 for r=1r = 1 and 37,748,736 for r=8r = 8. These are the "4.7M" and "37.7M" budgets of Table 4 of Hu and colleagues.

Correctness

The full proofs are in proofs/correctness.md. Associativity gives W0x+sB(Ax)=(W0+sBA)xW_0 x + s B (A x) = (W_0 + s B A) x, so the merged layer of line L9 computes the same function as lines L3 and L4, and line L10 recovers W0W_0. The column space of BAB A lies in the span of the rr columns of BB, so the update has rank at most rr; conversely, the singular value decomposition of any update of rank at most rr gives factors BB and AA that reach it. Line L2 makes the update zero, so the first forward pass equals the pretrained one. The chain rule gives lines L6 to L8: if G=gx⊤G = g x^\top is the gradient of full fine-tuning with respect to Δ\Delta, then ∇B=sGA⊤\nabla_B = s G A^\top and ∇A=sB⊤G\nabla_A = s B^\top G. At the start B=0B = 0, so ∇A=0\nabla_A = 0 and only BB moves in the first step.

Proof: The LoRA layer equals the merged layer, its update has rank at most r and reaches every update of rank at most r, training starts at the pretrained layer, and the gradients of A and B are the full gradient projected through the factorsfull

We use the notation of the page. W0W_0 is d×kd \times k, BB is d×rd \times r, AA is r×kr \times k, x∈Rkx \in \mathbb{R}^k, s=α/rs = \alpha / r and r≥1r \ge 1. The layer computes h=W0x+sB(Ax)h = W_0 x + s B (A x). We work in exact real arithmetic (the real RAM); the last section says what changes in floating point.

Claim 1: the factored layer and the merged layer agree

Let W=W0+sBAW = W_0 + s B A. Matrix multiplication is associative and distributes over addition, so

Wx=W0x+s(BA)x=W0x+sB(Ax)=h.W x = W_0 x + s (B A) x = W_0 x + s B (A x) = h.

Lines L3 and L4 compute the right side, and line L9 computes WW. So the merged layer and the factored layer give the same output for every xx. Line L10 computes W−sBA=W0W - s B A = W_0, so unmerging returns the pretrained matrix exactly. Because the two forms agree for every input, they agree for every batch of nn tokens, and for every network that contains the layer.

Claim 2: the update has rank at most r

The column space of BAB A is contained in the column space of BB, because (BA)y=B(Ay)(B A) y = B (A y) for every yy. The column space of BB is spanned by its rr columns, so it has dimension at most rr. Hence rank⁡(sBA)≤rank⁡(BA)≤min⁡(r,d,k)\operatorname{rank}(s B A) \le \operatorname{rank}(B A) \le \min(r, d, k), where the bound by dd and kk holds for every d×kd \times k matrix.

Claim 3: every update of rank at most r is reachable

Let Δ\Delta be a d×kd \times k matrix of rank q≤rq \le r. By the singular value decomposition, Δ=∑i=1qσiuivi⊤\Delta = \sum_{i=1}^{q} \sigma_i u_i v_i^\top. Put P=[σ1u1,…,σquq,0,…,0]P = [\sigma_1 u_1, \ldots, \sigma_q u_q, 0, \ldots, 0] (d×rd \times r) and Q=[v1,…,vq,0,…,0]⊤Q = [v_1, \ldots, v_q, 0, \ldots, 0]^\top (r×kr \times k), so Δ=PQ\Delta = P Q. Then B=PB = P and A=Q/sA = Q / s give sBA=Δs B A = \Delta. So the set of updates that LoRA of rank rr can express is exactly the set of d×kd \times k matrices of rank at most rr. The factors are not unique: BGB G and G−1AG^{-1} A give the same product for every invertible r×rr \times r matrix GG.

Claim 4: training starts at the pretrained layer

Line L2 sets B=0B = 0, so sBA=0s B A = 0 and h=W0xh = W_0 x for every xx, whatever the random AA of line L1. So before the first step the adapted network computes exactly the pretrained network.

Claim 5: the gradients

Let ℓ\ell be a differentiable loss of hh, and let g=∂ℓ/∂h∈Rdg = \partial \ell / \partial h \in \mathbb{R}^d. Write u=Axu = A x and c=B⊤gc = B^\top g. The output is hi=(W0x)i+s∑pBipuph_i = (W_0 x)_i + s \sum_{p} B_{ip} u_p with up=∑jApjxju_p = \sum_j A_{pj} x_j.

For BB: ∂hi/∂Bip=sup\partial h_i / \partial B_{ip} = s u_p, and hi′h_{i'} for i′≠ii' \ne i does not depend on BipB_{ip}. By the chain rule ∂ℓ/∂Bip=gisup\partial \ell / \partial B_{ip} = g_i s u_p, so ∇Bℓ=s gu⊤\nabla_B \ell = s\, g u^\top. This is line L6.

For AA: ∂hi/∂Apj=sBipxj\partial h_i / \partial A_{pj} = s B_{ip} x_j. So ∂ℓ/∂Apj=s∑igiBipxj=s cpxj\partial \ell / \partial A_{pj} = s \sum_i g_i B_{ip} x_j = s\, c_p x_j, and ∇Aℓ=s cx⊤=sB⊤gx⊤\nabla_A \ell = s\, c x^\top = s B^\top g x^\top. This is line L7.

For xx: ∂hi/∂xj=(W0)ij+s(BA)ij\partial h_i / \partial x_j = (W_0)_{ij} + s (B A)_{ij}. So ∇xℓ=W0⊤g+sA⊤B⊤g=W0⊤g+sA⊤c\nabla_x \ell = W_0^\top g + s A^\top B^\top g = W_0^\top g + s A^\top c. This is line L8.

The full fine-tuning gradient of the same loss with respect to an update Δ\Delta (with h=(W0+Δ)xh = (W_0 + \Delta) x) is G=gx⊤G = g x^\top. The two formulas above say ∇Bℓ=s GA⊤\nabla_B \ell = s\, G A^\top and ∇Aℓ=sB⊤G\nabla_A \ell = s B^\top G: the LoRA gradients are the full gradient multiplied by the other factor. For a batch of nn tokens the loss is a sum over tokens, so each gradient is the sum of the per-token gradients.

Claim 6: the start is not a stationary point, but A = B = 0 is

At the start B=0B = 0, so c=B⊤g=0c = B^\top g = 0 and ∇Aℓ=0\nabla_A \ell = 0, while ∇Bℓ=s g(Ax)⊤\nabla_B \ell = s\, g (A x)^\top, which is non-zero when g≠0g \ne 0 and Ax≠0A x \ne 0. A random Gaussian AA has Ax≠0A x \ne 0 for x≠0x \ne 0 with probability 1. So the first step changes BB only, and from the second step on AA also moves. If both AA and BB start at zero, then u=0u = 0 and c=0c = 0, both gradients are zero for every loss, and gradient descent never leaves the start. This is why one factor must be random.

Floating point

In floating point the factored form and the merged form round in different places, so they agree only up to rounding. Each entry of WxW x and of W0x+sB(Ax)W_0 x + s B (A x) is a sum of O(k+r)O(k + r) products, so the two differ by O((k+r) u)O((k + r)\, u) times the size of the terms, with uu the unit roundoff; the tests use a tolerance of 10−1210^{-12} on entries of size about 1. Unmerging after merging returns W0W_0 up to one rounding per entry, and merging in a lower precision than W0W_0 (for example in 16-bit floats) loses more.

Complexity

The cost is counted in the real RAM, per token. Line L3 costs Θ(rk)\Theta(r k), line L4 costs Θ(dk)\Theta(d k) for W0xW_0 x and Θ(dr)\Theta(d r) for BuB u, so the forward pass costs Θ(dk+r(d+k))\Theta(d k + r (d + k)), against Θ(dk)\Theta(d k) for the frozen layer alone. Lines L5 to L8 cost the same order. Over nn tokens the time is Θ(n(dk+r(d+k)))\Theta(n (d k + r (d + k))). The merged layer costs Θ(dk)\Theta(d k), the same as the original. Merging costs Θ(dkr)\Theta(d k r) once.

The saving is in memory, not in arithmetic. The trained parameters, their gradients and their optimizer state take Θ(r(d+k))\Theta(r (d + k)) numbers instead of Θ(dk)\Theta(d k). The activations of the frozen network must still be stored for the backward pass, so the activation memory is about the same as in full fine-tuning. Hu and colleagues measured on GPT-3 175B a drop of the training VRAM from 1.2 TB to 350 GB, a checkpoint of 35 MB instead of 350 GB for r=4r = 4 on WqW_q and WvW_v, and a 25% higher training throughput (Section 4.2); these are measurements on their hardware.

Properties

  • No inference cost after merging (theorem). The merged matrix has the shape of W0W_0, so the merged network has the same cost and the same outputs as the factored one, up to rounding.
  • Starts at the pretrained network (theorem). With B=0B = 0 the output is W0xW_0 x for every input.
  • Rank bound (theorem). The update has rank at most rr, and every update of rank at most rr is reachable.
  • Not unique. (BG,G−1A)(B G, G^{-1} A) gives the same update as (B,A)(B, A) for every invertible r×rr \times r matrix GG. The loss surface in (A,B)(A, B) is not convex even when the loss is convex in Δ\Delta.
  • Task switching. Many tasks can share one copy of W0W_0 and keep only their own AA and BB. Unmerge one update and merge another to switch.
  • Full rank recovers full fine-tuning. With r=min⁡(d,k)r = \min(d, k), every update is reachable, as in full fine-tuning of that matrix, although the training dynamics differ.

Variants and improvements

  • Which matrices. Hu and colleagues adapt only the attention projections and freeze the feed-forward layers. Under a fixed budget of 18M parameters on GPT-3 175B, adapting both WqW_q and WvW_v with r=4r = 4 did better than one matrix with r=8r = 8 (Table 5). Later work, QLoRA among it, adapts every linear layer of the block.
  • QLoRA (Dettmers and colleagues 2023) stores the frozen W0W_0 in a 4-bit format and trains LoRA factors in higher precision, which lowers the memory further.
  • Adapters (Houlsby and colleagues 2019) insert small bottleneck layers in series with each block. They also train few parameters, but they add layers that run at inference time, so they add latency that LoRA avoids after merging.
  • The scale. Hu and colleagues report that with Adam, tuning α\alpha is roughly the same as tuning the learning rate if the initialization is scaled to match (Section 4.1). The form α/r\alpha / r is a heuristic choice, not a derived value, and other scales have been proposed.
  • Compression view. A rank-rr approximation of an already trained full update, by the truncated singular value decomposition, is the best rank-rr approximation in the Frobenius norm (Eckart and Young 1936). LoRA does not compute that; it trains the factors directly.

When to use it

Use LoRA when the full set of weights plus their optimizer state does not fit in memory, or when many fine-tuned versions of one large model must be stored or served. Use full fine-tuning when memory allows and the task is far from the pretraining data, because a low-rank update can underfit there; Hu and colleagues warn that a small rr need not work for every task. When the model is small, the saving matters less.

Pitfalls

  • Both factors at zero. If line L1 also sets A=0A = 0, then u=0u = 0 and c=0c = 0, both gradients are zero, and training never moves. One factor must be random. If AA is zero and BB random, the roles swap.
  • Forgetting the scale. Merging W0+BAW_0 + B A without s=α/rs = \alpha / r gives a different network from the one that was trained. Use the same ss in lines L4, L9 and L10.
  • Merging in low precision. Merging into a 16-bit or quantized W0W_0 rounds the update. Small updates can vanish under the rounding of large weights. Merge in a higher precision, or keep the factors apart.
  • Changing rr and keeping the learning rate. The scale α/r\alpha / r is meant to reduce retuning when rr changes, but the best learning rate still depends on rr and on the optimizer. Tune it on held out data.
  • Expecting less compute per step. The backward pass still runs through every frozen layer, so the time per step drops much less than the memory.
  • Batching different tasks. If each input of a batch uses a different adapter, the merged form cannot serve them together. Keep the factored form for such batches.

Implementations

The code implements one adapted layer: the initialization, the forward pass, the gradients of lines L6 to L8, the merge and the unmerge, and a gradient step on a small squared loss. It takes W0W_0 and the data as given; it does not train a large network and does not load pretrained weights. The tests check the rank-rr layer against the full update W0+sBAW_0 + s B A of the same product, the merged layer against the unmerged one, the rank bound with exact rational elimination, the gradients against central finite differences with h=10−6h = 10^{-6} and a tolerance of 10−510^{-5}, and a fit of a planted rank-2 change.

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

low_rank_adaptation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/low-rank-adaptation/. The authors are listed in prov/W05XMM.jsonl.

"""Low-rank adaptation (LoRA) of one frozen weight matrix.

Shapes, with named sizes:
    W0 is d x k (frozen, the pretrained weight; it maps k inputs to d outputs),
    B  is d x r (trained, zero at the start),
    A  is r x k (trained, random at the start),
    x  is a vector of k numbers (one token), g is a vector of d numbers.

The adapted layer computes h = W0 x + s B (A x) with the scale s = alpha / r.
The update s B A has rank at most r. merge() folds it into W0, so the merged
layer costs the same as the original one, and unmerge() takes it out again.

backward() returns the gradients of a loss with respect to A, B and x, given
g = dloss/dh. W0 gets no gradient: it is frozen.

Cost per token: Theta(d k + r (d + k)) for forward() and backward(), and
Theta(d k) for the merged layer. The trained parameters are r (d + k) numbers.

The code takes W0 and the data as given. It does not train a large network
and does not load pretrained weights.
"""

import math
import random
from typing import List, Sequence, Tuple

Matrix = List[List[float]]
Vector = List[float]


def matvec(M: Sequence[Sequence[float]], x: Sequence[float]) -> Vector:
    """Return M x."""
    return [math.fsum(row[j] * x[j] for j in range(len(x))) for row in M]


def matvec_t(M: Sequence[Sequence[float]], y: Sequence[float]) -> Vector:
    """Return M^T y."""
    cols = len(M[0])
    return [math.fsum(M[i][j] * y[i] for i in range(len(M))) for j in range(cols)]


def matmul(P: Sequence[Sequence[float]], Q: Sequence[Sequence[float]]) -> Matrix:
    """Return the product P Q."""
    inner, cols = len(Q), len(Q[0])
    return [[math.fsum(P[i][t] * Q[t][j] for t in range(inner)) for j in range(cols)] for i in range(len(P))]


def outer(u: Sequence[float], v: Sequence[float], s: float = 1.0) -> Matrix:
    """Return s u v^T."""
    return [[s * a * b for b in v] for a in u]


def _check_shapes(W0, A, B):
    d, k = len(W0), len(W0[0])
    r = len(A)
    if r < 1 or len(A[0]) != k or len(B) != d or any(len(row) != r for row in B):
        raise ValueError("need W0: d x k, A: r x k, B: d x r with r >= 1")
    return d, k, r


def init(d: int, k: int, r: int, rng: random.Random, sigma: float = 0.02) -> Tuple[Matrix, Matrix]:
    """Return (A, B): A has Gaussian entries of standard deviation sigma, B is zero."""
    if r < 1 or d < 1 or k < 1:
        raise ValueError("d, k and r must be at least 1")
    A = [[rng.gauss(0.0, sigma) for _ in range(k)] for _ in range(r)]  # @line L1
    B = [[0.0] * r for _ in range(d)]  # @line L2
    return A, B


def forward(W0: Matrix, A: Matrix, B: Matrix, alpha: float, x: Sequence[float]) -> Vector:
    """Return h = W0 x + (alpha / r) B (A x), without forming B A."""
    d, k, r = _check_shapes(W0, A, B)
    s = alpha / r
    u = matvec(A, x)  # @line L3
    bu = matvec(B, u)
    base = matvec(W0, x)
    return [base[i] + s * bu[i] for i in range(d)]  # @line L4


def backward(W0: Matrix, A: Matrix, B: Matrix, alpha: float, x: Sequence[float],
             g: Sequence[float]) -> Tuple[Matrix, Matrix, Vector]:
    """Return (grad_A, grad_B, grad_x) for one token, given g = dloss/dh."""
    d, k, r = _check_shapes(W0, A, B)
    s = alpha / r
    u = matvec(A, x)  # @line L5
    c = matvec_t(B, g)  # @line L5
    grad_B = outer(g, u, s)  # @line L6
    grad_A = outer(c, x, s)  # @line L7
    a_t_c = matvec_t(A, c)
    w_t_g = matvec_t(W0, g)
    grad_x = [w_t_g[j] + s * a_t_c[j] for j in range(k)]  # @line L8
    return grad_A, grad_B, grad_x


def delta(A: Matrix, B: Matrix, alpha: float) -> Matrix:
    """Return the full update (alpha / r) B A, a d x k matrix of rank at most r."""
    r = len(A)
    BA = matmul(B, A)
    return [[alpha / r * v for v in row] for row in BA]


def merge(W0: Matrix, A: Matrix, B: Matrix, alpha: float) -> Matrix:
    """Return W = W0 + (alpha / r) B A."""
    _check_shapes(W0, A, B)
    D = delta(A, B, alpha)
    return [[W0[i][j] + D[i][j] for j in range(len(W0[0]))] for i in range(len(W0))]  # @line L9


def unmerge(W: Matrix, A: Matrix, B: Matrix, alpha: float) -> Matrix:
    """Return W0 = W - (alpha / r) B A, the inverse of merge up to rounding."""
    _check_shapes(W, A, B)
    D = delta(A, B, alpha)
    return [[W[i][j] - D[i][j] for j in range(len(W[0]))] for i in range(len(W))]  # @line L10


def forward_batch(W0: Matrix, A: Matrix, B: Matrix, alpha: float, X: Sequence[Sequence[float]]) -> Matrix:
    """Apply forward() to each of the n token rows of X (an n x k matrix)."""
    return [forward(W0, A, B, alpha, x) for x in X]


def backward_batch(W0: Matrix, A: Matrix, B: Matrix, alpha: float, X: Sequence[Sequence[float]],
                   G: Sequence[Sequence[float]]) -> Tuple[Matrix, Matrix]:
    """Return (grad_A, grad_B) summed over the n tokens, given G = dloss/dH (n x d)."""
    d, k, r = _check_shapes(W0, A, B)
    gA = [[0.0] * k for _ in range(r)]
    gB = [[0.0] * r for _ in range(d)]
    for x, g in zip(X, G):
        a, b, _ = backward(W0, A, B, alpha, x, g)
        for i in range(r):
            for j in range(k):
                gA[i][j] += a[i][j]
        for i in range(d):
            for j in range(r):
                gB[i][j] += b[i][j]
    return gA, gB


def squared_loss(W0: Matrix, A: Matrix, B: Matrix, alpha: float, X, Y) -> Tuple[float, Matrix]:
    """Return (loss, G) for loss = (1 / (2 n)) sum_t |h_t - y_t|^2 and G = dloss/dH."""
    n = len(X)
    H = forward_batch(W0, A, B, alpha, X)
    G = [[(H[t][i] - Y[t][i]) / n for i in range(len(H[t]))] for t in range(n)]
    loss = math.fsum((H[t][i] - Y[t][i]) ** 2 for t in range(n) for i in range(len(H[t]))) / (2 * n)
    return loss, G


def sgd_step(W0: Matrix, A: Matrix, B: Matrix, alpha: float, X, Y, lr: float) -> float:
    """Do one gradient step on A and B for the squared loss, in place. Return the loss before the step."""
    loss, G = squared_loss(W0, A, B, alpha, X, Y)
    gA, gB = backward_batch(W0, A, B, alpha, X, G)
    for i in range(len(A)):
        for j in range(len(A[0])):
            A[i][j] -= lr * gA[i][j]
    for i in range(len(B)):
        for j in range(len(B[0])):
            B[i][j] -= lr * gB[i][j]
    return loss


def trainable_parameters(d: int, k: int, r: int) -> int:
    """Return r (d + k), the number of entries of A and B."""
    return r * (d + k)
test_low_rank_adaptation.py 240 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/low-rank-adaptation/. The authors are listed in prov/W05XMM.jsonl.

import math
import random
from fractions import Fraction

import pytest

from low_rank_adaptation import (backward, backward_batch, delta, forward, forward_batch, init, matmul,
                                 matvec, merge, sgd_step, squared_loss, trainable_parameters, unmerge)


def rand_matrix(rng, rows, cols, scale=1.0):
    return [[rng.gauss(0.0, scale) for _ in range(cols)] for _ in range(rows)]


def rand_vector(rng, n, scale=1.0):
    return [rng.gauss(0.0, scale) for _ in range(n)]


def close(u, v, tol):
    return all(abs(a - b) <= tol for a, b in zip(u, v))


def exact_rank(M):
    """Rank of a matrix of integers by Gaussian elimination in Fraction."""
    R = [[Fraction(v) for v in row] for row in M]
    rows, cols = len(R), len(R[0])
    rank, col = 0, 0
    while rank < rows and col < cols:
        piv = next((i for i in range(rank, rows) if R[i][col] != 0), None)
        if piv is None:
            col += 1
            continue
        R[rank], R[piv] = R[piv], R[rank]
        for i in range(rows):
            if i != rank and R[i][col] != 0:
                f = R[i][col] / R[rank][col]
                R[i] = [R[i][j] - f * R[rank][j] for j in range(cols)]
        rank += 1
        col += 1
    return rank


# A worked example of the page: d = 2, k = 3, r = 1, alpha = 2, so s = 2.
W0_EX = [[1.0, 0.0, 2.0], [0.0, 1.0, -1.0]]
A_EX = [[1.0, 2.0, 0.0]]
B_EX = [[0.5], [-1.0]]
X_EX = [1.0, 1.0, 1.0]


def test_worked_example():
    h = forward(W0_EX, A_EX, B_EX, 2.0, X_EX)
    assert h == pytest.approx([6.0, -6.0], abs=1e-12)
    W = merge(W0_EX, A_EX, B_EX, 2.0)
    assert W == [[2.0, 2.0, 2.0], [-2.0, -3.0, -1.0]]
    assert matvec(W, X_EX) == pytest.approx(h, abs=1e-12)


def test_at_init_the_output_is_the_pretrained_output():
    rng = random.Random(1)
    d, k, r = 5, 4, 2
    W0 = rand_matrix(rng, d, k)
    A, B = init(d, k, r, rng, sigma=0.5)
    for _ in range(5):
        x = rand_vector(rng, k)
        assert forward(W0, A, B, 16.0, x) == pytest.approx(matvec(W0, x), abs=1e-15)


def test_at_init_only_B_gets_a_gradient():
    rng = random.Random(2)
    d, k, r = 5, 4, 3
    W0 = rand_matrix(rng, d, k)
    A, B = init(d, k, r, rng, sigma=0.5)
    x, g = rand_vector(rng, k), rand_vector(rng, d)
    gA, gB, _ = backward(W0, A, B, 3.0, x, g)
    assert all(v == 0.0 for row in gA for v in row)
    assert any(abs(v) > 1e-6 for row in gB for v in row)


def test_zero_A_and_zero_B_is_stuck():
    rng = random.Random(3)
    d, k, r = 4, 3, 2
    W0 = rand_matrix(rng, d, k)
    A = [[0.0] * k for _ in range(r)]
    B = [[0.0] * r for _ in range(d)]
    gA, gB, _ = backward(W0, A, B, 1.0, rand_vector(rng, k), rand_vector(rng, d))
    assert all(v == 0.0 for row in gA + gB for v in row)


def test_rank_r_matches_the_full_update_of_the_same_product():
    rng = random.Random(4)
    for d, k, r in [(6, 5, 1), (6, 5, 2), (4, 7, 3), (8, 8, 8)]:
        W0 = rand_matrix(rng, d, k)
        A, B = rand_matrix(rng, r, k), rand_matrix(rng, d, r)
        alpha = 2.0 * r
        D = delta(A, B, alpha)
        for _ in range(4):
            x = rand_vector(rng, k)
            full = [a + b for a, b in zip(matvec(W0, x), matvec(D, x))]
            assert close(forward(W0, A, B, alpha, x), full, 1e-12)


def test_merged_equals_unmerged_and_unmerge_restores_W0():
    rng = random.Random(5)
    d, k, r = 7, 6, 2
    W0 = rand_matrix(rng, d, k)
    A, B = rand_matrix(rng, r, k), rand_matrix(rng, d, r)
    W = merge(W0, A, B, 4.0)
    X = [rand_vector(rng, k) for _ in range(6)]
    for h, x in zip(forward_batch(W0, A, B, 4.0, X), X):
        assert close(h, matvec(W, x), 1e-12)
    back = unmerge(W, A, B, 4.0)
    assert all(close(a, b, 1e-12) for a, b in zip(back, W0))


def test_update_has_rank_at_most_r():
    rng = random.Random(6)
    for d, k, r in [(5, 4, 1), (5, 4, 2), (6, 6, 3), (3, 6, 5)]:
        A = [[rng.randint(-3, 3) for _ in range(k)] for _ in range(r)]
        B = [[rng.randint(-3, 3) for _ in range(r)] for _ in range(d)]
        BA = [[int(v) for v in row] for row in matmul(B, A)]
        assert exact_rank(BA) <= min(r, d, k)
    # Generic integer factors reach rank r exactly.
    A = [[1, 0, 2, 1], [0, 1, 1, 3]]
    B = [[1, 0], [0, 1], [1, 1], [2, -1]]
    assert exact_rank([[int(v) for v in row] for row in matmul(B, A)]) == 2


def test_every_rank_r_update_is_reachable():
    # Delta = P Q with P: d x r and Q: r x k is reached with B = P and A = Q r / alpha.
    rng = random.Random(7)
    d, k, r, alpha = 5, 4, 2, 8.0
    P, Q = rand_matrix(rng, d, r), rand_matrix(rng, r, k)
    target = matmul(P, Q)
    A = [[v * r / alpha for v in row] for row in Q]
    D = delta(A, P, alpha)
    assert all(close(a, b, 1e-12) for a, b in zip(D, target))


def test_parameter_counts():
    assert trainable_parameters(12288, 12288, 1) == 24576
    assert trainable_parameters(12288, 12288, 4) == 98304
    assert 96 * 2 * trainable_parameters(12288, 12288, 1) == 4718592
    assert 96 * 2 * trainable_parameters(12288, 12288, 8) == 37748736


def test_gradients_against_finite_differences():
    rng = random.Random(8)
    d, k, r, alpha = 4, 3, 2, 3.0
    W0 = rand_matrix(rng, d, k)
    A, B = rand_matrix(rng, r, k), rand_matrix(rng, d, r)
    x, c = rand_vector(rng, k), rand_vector(rng, d)

    def loss(A_, B_, x_):
        # A smooth loss of h: sum_i c_i h_i + 0.5 h_i^2, so g_i = c_i + h_i.
        h = forward(W0, A_, B_, alpha, x_)
        return math.fsum(ci * hi + 0.5 * hi * hi for ci, hi in zip(c, h))

    h = forward(W0, A, B, alpha, x)
    g = [ci + hi for ci, hi in zip(c, h)]
    gA, gB, gx = backward(W0, A, B, alpha, x, g)
    eps = 1e-6
    for M, G in ((A, gA), (B, gB)):
        for i in range(len(M)):
            for j in range(len(M[0])):
                old = M[i][j]
                M[i][j] = old + eps
                up = loss(A, B, x)
                M[i][j] = old - eps
                down = loss(A, B, x)
                M[i][j] = old
                assert (up - down) / (2 * eps) == pytest.approx(G[i][j], abs=1e-5)
    for j in range(k):
        xp, xm = list(x), list(x)
        xp[j] += eps
        xm[j] -= eps
        assert (loss(A, B, xp) - loss(A, B, xm)) / (2 * eps) == pytest.approx(gx[j], abs=1e-5)


def test_gradients_are_the_full_gradient_projected():
    # dloss/dDelta = g x^T; then grad_B = s (g x^T) A^T and grad_A = s B^T (g x^T).
    rng = random.Random(9)
    d, k, r, alpha = 5, 4, 2, 2.0
    s = alpha / r
    W0 = rand_matrix(rng, d, k)
    A, B = rand_matrix(rng, r, k), rand_matrix(rng, d, r)
    x, g = rand_vector(rng, k), rand_vector(rng, d)
    gA, gB, _ = backward(W0, A, B, alpha, x, g)
    full = [[gi * xj for xj in x] for gi in g]
    At = [list(col) for col in zip(*A)]
    Bt = [list(col) for col in zip(*B)]
    want_B = [[s * v for v in row] for row in matmul(full, At)]
    want_A = [[s * v for v in row] for row in matmul(Bt, full)]
    assert all(close(a, b, 1e-12) for a, b in zip(gB, want_B))
    assert all(close(a, b, 1e-12) for a, b in zip(gA, want_A))


def test_batch_gradient_is_the_sum_over_tokens():
    rng = random.Random(10)
    d, k, r, alpha = 3, 4, 2, 1.0
    W0 = rand_matrix(rng, d, k)
    A, B = rand_matrix(rng, r, k), rand_matrix(rng, d, r)
    X = [rand_vector(rng, k) for _ in range(3)]
    G = [rand_vector(rng, d) for _ in range(3)]
    gA, gB = backward_batch(W0, A, B, alpha, X, G)
    sA = [[0.0] * k for _ in range(r)]
    for x, g in zip(X, G):
        a, _, _ = backward(W0, A, B, alpha, x, g)
        sA = [[sA[i][j] + a[i][j] for j in range(k)] for i in range(r)]
    assert all(close(a, b, 1e-12) for a, b in zip(gA, sA))


def test_training_fits_a_planted_rank_r_change():
    # The pretrained W0 is frozen; the target layer is W0 + P Q with rank 2.
    rng = random.Random(11)
    d, k, r, alpha = 4, 3, 2, 2.0
    W0 = rand_matrix(rng, d, k)
    P, Q = rand_matrix(rng, d, r), rand_matrix(rng, r, k)
    W_target = [[a + b for a, b in zip(r0, r1)] for r0, r1 in zip(W0, matmul(P, Q))]
    X = [[1.0 if i == j else 0.0 for j in range(k)] for i in range(k)]
    Y = [matvec(W_target, x) for x in X]
    A, B = init(d, k, r, rng, sigma=0.5)
    first = None
    for _ in range(1500):
        loss = sgd_step(W0, A, B, alpha, X, Y, lr=0.5)
        first = loss if first is None else first
    final, _ = squared_loss(W0, A, B, alpha, X, Y)
    assert first > 0.05
    assert final < 1e-10
    W = merge(W0, A, B, alpha)
    assert all(close(a, b, 1e-4) for a, b in zip(W, W_target))


def test_shape_errors():
    with pytest.raises(ValueError):
        forward([[1.0, 2.0]], [[1.0]], [[1.0]], 1.0, [1.0, 1.0])
    with pytest.raises(ValueError):
        init(2, 2, 0, random.Random(0))

History

Aghajanyan, Gupta and Zettlemoyer (2021) measured that fine-tuning a pretrained language model in a random subspace of small dimension recovers most of the result of full fine-tuning. Earlier parameter-efficient methods trained adapter layers (Houlsby and colleagues 2019), prompts or prefixes. Hu and colleagues (2021, published at ICLR 2022) proposed to train a low-rank update of the existing weight matrices instead, with BB at zero and AA random, and showed that it can be merged into the weights. On GPT-3 175B they reported, in Table 4, a WikiSQL accuracy of 73.4 with 4.7M trained parameters and 74.0 with 37.7M, against 73.8 for full fine-tuning, and a MultiNLI-matched accuracy of 91.7 and 91.6 against 89.5. These are measurements on their setup. LoRA then became a common way to fine-tune large open models, often with a quantized base model (QLoRA, 2023).

References

  1. Edward J. Hu, Yelong Shen, Phillip Wallis, Zeyuan Allen-Zhu, Yuanzhi Li, Shean Wang, Lu Wang and Weizhu Chen, LoRA: Low-rank adaptation of large language models, ICLR 2022, Section 4.1 (equation 3, the Gaussian A and zero B, the scale alpha / r, merging with no extra latency), Section 4.2 (W_q and W_v, the VRAM and checkpoint savings on GPT-3 175B), Table 4 (GPT-3 175B results), Section 7.1 and Table 5 (which matrices), Section 7.2 and Table 6 (the rank r)
  2. Armen Aghajanyan, Sonal Gupta and Luke Zettlemoyer, Intrinsic dimensionality explains the effectiveness of language model fine-tuning, ACL-IJCNLP 2021, the measurements of the intrinsic dimension of fine-tuning, which motivate the low-rank hypothesis
  3. Neil Houlsby, Andrei Giurgiu, Stanislaw Jastrzebski, Bruna Morrone, Quentin de Laroussilhe, Andrea Gesmundo, Mona Attariyan and Sylvain Gelly, Parameter-efficient transfer learning for NLP, ICML 2019, the adapter layers, the earlier parameter-efficient method that adds inference latency
  4. Tim Dettmers, Artidoro Pagnoni, Ari Holtzman and Luke Zettlemoyer, QLoRA: Efficient finetuning of quantized LLMs, NeurIPS 2023, LoRA on top of a frozen 4-bit quantized base model

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example