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
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 of shape , it freezes and trains two small matrices () and () with a rank much smaller than and . The layer computes . starts at zero, so training starts exactly at the pretrained network. After training, can be added into , 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 that maps an input to , for example the query projection of an attention layer, with . Full fine-tuning learns an update of the same shape, so new numbers per matrix, plus the optimizer state for each of them. LoRA restricts the update to the form
so it trains 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 already does well on WikiSQL and MultiNLI for GPT-3 175B when both and are adapted, and they say that they do not expect a small to work for every task. The scale is a constant; Hu and colleagues set to the first they try and do not tune it, so that changing later needs less retuning of the learning rate.
For a sequence of tokens, is and the output is , of shape .
The algorithm
The algorithm has an initialization, a forward pass, a backward pass that gives the gradients of and (and of the input, for the layers below), and the merge and unmerge steps. is never changed during training. The optimizer (for example AdamW) updates and with the gradients of lines L6 and L7.
LORA-INIT(d, k, r, σ)- 1
A ← r × k matrix with entries drawn from N(0, σ^2) - 2
B ← d × r zero matrix LORA-FORWARD(W0, A, B, α, x) ▷ x: k numbers, s = α / r- 3
u ← A x ▷ r numbers - 4
return h ← W0 x + s B u ▷ d numbers, B A is never formed LORA-BACKWARD(W0, A, B, α, x, g) ▷ g = ∂ℓ/∂h: d numbers- 5
u ← A x; c ← B^T g ▷ r numbers each - 6
∇B ← s g u^T ▷ d × r - 7
∇A ← s c x^T ▷ r × k - 8
∇x ← W0^T g + s A^T c ▷ k numbers LORA-MERGE(W0, A, B, α)- 9
return W ← W0 + s B A LORA-UNMERGE(W, A, B, α)- 10
return W0 ← W - s B A
For a batch of tokens the gradients of and are the sums of lines L6 and L7 over the tokens.
Example
Take , , and , so , with
| step | value |
|---|---|
| L3 | 3 |
| (3, 0) | |
| (3, -6) | |
| L4 | (6, -6) |
| L9 | rows (1, 2, 0) and (-2, -4, 0) |
| L9 | rows (2, 2, 2) and (-2, -3, -1) |
| (6, -6), the same as L4 |
The update has rank 1, as both of its rows are multiples of . With (line L2) the same input gives , the pretrained output.
At scale, take GPT-3 175B, which has 96 layers and . One matrix has 150,994,944 entries. LoRA with on that matrix trains numbers. Adapting and in all 96 layers trains numbers: 4,718,592 for and 37,748,736 for . 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 , so the merged layer of line L9 computes the same function as lines L3 and L4, and line L10 recovers . The column space of lies in the span of the columns of , so the update has rank at most ; conversely, the singular value decomposition of any update of rank at most gives factors and 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 is the gradient of full fine-tuning with respect to , then and . At the start , so and only 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. is , is , is , , and . The layer computes . 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 . Matrix multiplication is associative and distributes over addition, so
Lines L3 and L4 compute the right side, and line L9 computes . So the merged layer and the factored layer give the same output for every . Line L10 computes , so unmerging returns the pretrained matrix exactly. Because the two forms agree for every input, they agree for every batch of tokens, and for every network that contains the layer.
Claim 2: the update has rank at most r
The column space of is contained in the column space of , because for every . The column space of is spanned by its columns, so it has dimension at most . Hence , where the bound by and holds for every matrix.
Claim 3: every update of rank at most r is reachable
Let be a matrix of rank . By the singular value decomposition, . Put () and (), so . Then and give . So the set of updates that LoRA of rank can express is exactly the set of matrices of rank at most . The factors are not unique: and give the same product for every invertible matrix .
Claim 4: training starts at the pretrained layer
Line L2 sets , so and for every , whatever the random of line L1. So before the first step the adapted network computes exactly the pretrained network.
Claim 5: the gradients
Let be a differentiable loss of , and let . Write and . The output is with .
For : , and for does not depend on . By the chain rule , so . This is line L6.
For : . So , and . This is line L7.
For : . So . This is line L8.
The full fine-tuning gradient of the same loss with respect to an update (with ) is . The two formulas above say and : the LoRA gradients are the full gradient multiplied by the other factor. For a batch of 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 , so and , while , which is non-zero when and . A random Gaussian has for with probability 1. So the first step changes only, and from the second step on also moves. If both and start at zero, then and , 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 and of is a sum of products, so the two differ by times the size of the terms, with the unit roundoff; the tests use a tolerance of on entries of size about 1. Unmerging after merging returns up to one rounding per entry, and merging in a lower precision than (for example in 16-bit floats) loses more.
Complexity
The cost is counted in the real RAM, per token. Line L3 costs , line L4 costs for and for , so the forward pass costs , against for the frozen layer alone. Lines L5 to L8 cost the same order. Over tokens the time is . The merged layer costs , the same as the original. Merging costs once.
The saving is in memory, not in arithmetic. The trained parameters, their gradients and their optimizer state take numbers instead of . 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 on and , 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 , 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 the output is for every input.
- Rank bound (theorem). The update has rank at most , and every update of rank at most is reachable.
- Not unique. gives the same update as for every invertible matrix . The loss surface in is not convex even when the loss is convex in .
- Task switching. Many tasks can share one copy of and keep only their own and . Unmerge one update and merge another to switch.
- Full rank recovers full fine-tuning. With , 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 and with did better than one matrix with (Table 5). Later work, QLoRA among it, adapts every linear layer of the block.
- QLoRA (Dettmers and colleagues 2023) stores the frozen 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 is roughly the same as tuning the learning rate if the initialization is scaled to match (Section 4.1). The form is a heuristic choice, not a derived value, and other scales have been proposed.
- Compression view. A rank- approximation of an already trained full update, by the truncated singular value decomposition, is the best rank- 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 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 , then and , both gradients are zero, and training never moves. One factor must be random. If is zero and random, the roles swap.
- Forgetting the scale. Merging without gives a different network from the one that was trained. Use the same in lines L4, L9 and L10.
- Merging in low precision. Merging into a 16-bit or quantized rounds the update. Small updates can vanish under the rounding of large weights. Merge in a higher precision, or keep the factors apart.
- Changing and keeping the learning rate. The scale is meant to reduce retuning when changes, but the best learning rate still depends on 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 and the data as given; it does not train a large network and does not load pretrained weights. The tests check the rank- layer against the full update 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 and a tolerance of , 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.
# 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 at zero and 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
- 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)
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag W05XMM Edit this page History Report an error Markdown