LoRA from scratch
LoRA comes up in ML fundamentals screens as a quick "explain LoRA", and in interviews given over to fine-tuning. The strongest answer is one you can also write. As a coding question, it reads like this:
Write
LoRALinear(base, r, alpha), a layer that wraps an existingnn.Linear, in four levels.
- Freeze the base layer. The only parts that train are
A, which isrbyin_features, andB, which isout_featuresbyr. Right after wrapping, the layer gives exactly the base layer's output.forward(x)returnsbase(x) + (alpha / r) * x @ A.T @ B.T, and the layer learns a low-rank change.merge()folds the update intobase.weight, so inference costs nothing extra, andunmerge()takes it back out. A merged layer must not add the update a second time.add_lora(model, r, alpha, targets)wraps everynn.Linearnamed intargets, anywhere in a model, and freezes everything else.As you go, tell me why
Bstarts at zero and notA, whatalpha / rbuys you, and how many numbers train.
Here is the finished class on a small layer, nn.Linear(16, 12), wrapped at r = 4 and alpha = 8:
| Check | Result |
|---|---|
| numbers that train | 112: A holds 4 × 16, and B holds 12 × 4 |
| numbers that stay frozen | 204: the base's 192 weights and 12 biases |
torch.equal(lora(x), base(x)), right after wrapping | True |
the outputs after merge(), once training has moved B | the same as before the merge |
base.weight after unmerge() | the pretrained weight again |
The class is short. The interview is in the reason behind each line, and in the follow-ups: which layers to adapt, QLoRA, and serving many adapters on one model. The lesson starts with what LoRA trains and why that saves so much, then builds the class one piece at a time. At the end you write all four levels yourself, as the practice problem, in about 45 minutes.