Linear algebra for LLMsPart 7: Decompositions and low rank
LoRA
7 min
Freeze the weight, learn a low-rank update
LoRA (low-rank adaptation) keeps the pretrained fixed and trains two thin matrices. Their product has ’s shape but rank at most (Part 3), with small: 8, 16 or 64.
Write
In the forward pass
In nn.Linear layout: maps the input down to numbers, maps them back up. The product is never formed during training (Part 2’s cheap ordering).
starts at zero
starts random and starts at zero, so training begins from exactly the pretrained model and the update grows from nothing. scales the update so that changing needs less retuning of the learning rate.
Write
How many parameters
0.39% of the matrix. Gradients and optimizer state are only needed for these, which is where most of LoRA’s memory saving comes from.
Write
✏️ Your turn
Adapt a real model
How many LoRA parameters if you adapt and in every layer? Roughly what fraction of 8.03B is that?
Work it out on paper, then go to the next card to check.
Answer: about 6.8 million
Under a tenth of a percent of the model. The original LoRA paper found that adapting these two projections alone worked well.
Merge for free inference
After training, add the update into the weight once. The merged layer is an ordinary matrix of the same shape: no extra parameters or FLOPs at inference. (Or keep it separate, to swap many adapters on one base model.)
Write
In code
class LoRALinear(nn.Module):
def __init__(self, base: nn.Linear, r=8, alpha=16):
super().__init__()
self.base, self.scale = base, alpha / r
self.A = nn.Parameter(torch.randn(r, base.in_features) / r)
self.B = nn.Parameter(torch.zeros(base.out_features, r))
base.weight.requires_grad_(False)
def forward(self, x):
return self.base(x) + self.scale * (x @ self.A.T) @ self.B.TA sketch of the idea; libraries such as PEFT add dropout, initialization choices and merging.
📌 Recap
LoRA in one card
- , , , frozen.
- at the start, so training begins at the pretrained model.
- parameters per adapted matrix.
- Merge after training: no inference cost.
Write