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 . It learns the change to as the product of two thin matrices:
is the change that fine-tuning makes. has columns and has rows, with small, like 8. Only and train. Drag the rank:
W12 × 16, frozenB12 × 4A4 × 16- W, frozen
- 192
- A and B, trained
- 112
- GPT-3 Wq, full
- 150,994,944
- GPT-3 Wq, LoRA
- 98,304, 0.065%
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. can hold at most directions, which is why is called the rank.
The frozen is shared by every task. A task's whole fine-tune is the and of each layer you adapted.
The forward pass adds a small branch to the frozen layer
The input goes through the frozen as before. It also goes through and then , a small side path called the branch. Step through it:
The branch's output is added on, scaled by :
Here is the layer's output. (alpha) is a number you choose, like , 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 . 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.