3/31
Part 1 of 6 · What LoRA trainsLearn and do

LoRA trains two thin matrices, B and A, and leaves W alone

LoRA, short for low-rank adaptation (Hu et al., 2021), freezes each pretrained weight matrix WW. It learns the change to WW as the product of two thin matrices:

W+ΔW=W+BAW + \Delta W = W + BA

ΔW\Delta W is the change that fine-tuning makes. BB has rr columns and AA has rr rows, with rr small, like 8. Only AA and BB train. Drag the rank:

One frozen W, one small pair per taskInteractive
W, frozen
192
A and B, trained
112
GPT-3 Wq, full
150,994,944
GPT-3 Wq, LoRA
98,304, 0.065%
At r = 4, A and B hold r × (in + out) = 4 × (16 + 12) = 112 numbers, against 192 in W. On GPT-3's 12,288-wide query projection the same rank trains 98,304 numbers, 0.065% of its 150,994,944.

Why can so few numbers be enough? The paper's hypothesis is that the change fine-tuning makes has a low intrinsic rank. A matrix's rank counts the independent directions it holds, and the change needs only a few. BABA can hold at most rr directions, which is why rr is called the rank.

The frozen WW is shared by every task. A task's whole fine-tune is the AA and BB of each layer you adapted.

The forward pass adds a small branch to the frozen layer

The input goes through the frozen WW as before. It also goes through AA and then BB, a small side path called the branch. Step through it:

One LoRA layerInteractive
xWAuB+h
forward, values backward, gradients
x goes through the frozen W as before.

The branch's output is added on, scaled by α/r\alpha / r:

h=Wx+αrBAxh = Wx + \frac{\alpha}{r} BAx

Here hh is the layer's output. α\alpha (alpha) is a number you choose, like rr, and neither one trains. In the editor, W is a frozen weight with 16 inputs and 12 outputs, A and B are a rank-4 pair, and scale is α/r\alpha / r. x holds 5 inputs, one per row, so the frozen layer computes x @ W.T. Set h: the frozen layer's output plus the scaled branch. Then set rank, the rank of B @ A, and same: whether h equals one plain layer with the weight W + scale * (B @ A). Compare those two with torch.allclose, because they add in a different order and round differently in the last digits.