Lesson 2 · Unit 03
LoRA
Learn a low-rank change beside a frozen weight matrix
What you practise
- Leave
Wfrozen and learn a low-rank updateB·A - Rank and alpha
- Counting trainable parameters for a given layer
- Why
Bstarts at zero - Merging the adapter back
Try a question from this lesson
Pick one
A layer has 6 inputs and 4 outputs, and its adapter has rank 2. What does this print: the shape of the change B·A?
d_in, d_out, r = 6, 4, 2
A = torch.randn(r, d_in)
B = torch.zeros(d_out, r)
print(tuple((B @ A).shape))Hint
A matrix product keeps the rows of the left factor and the columns of the right one.
Correct answer
(4, 6)
Why
(4, 2) times (2, 6) is (4, 6): outputs by inputs, the shape nn.Linear gives its own weight. The change is a full-size matrix, but every entry of it is determined by the 20 numbers in A and B.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
A low-rank detour
LoRA freezes the pretrained matrix W and learns its change as a product of two small matrices: A with shape (r, inputs) and B with shape (outputs, r). The number r is the rank, usually a handful.
The layer adds the detour through A and B, scaled by alpha / r, to what W already computes. Only A and B are trained.
def forward(x):
delta = x @ A.T @ B.T
return x @ W.T + (alpha / r) * deltaConcept
Merging
Once trained, the adapter is just a matrix to add: W + (alpha / r) * B @ A has the same shape as W. Add it once and the layer is an ordinary layer again, with no extra work at inference.
Or keep the adapter separate. One base model can then serve many tasks, each with its own small pair of matrices swapped in.
10 more exercises in the app
- 3× type the answer
- 4× multiple choice
- 1× true or false
- 1× fill the blanks
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.