1/31
Learn

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 existing nn.Linear, in four levels.

  1. Freeze the base layer. The only parts that train are A, which is r by in_features, and B, which is out_features by r. Right after wrapping, the layer gives exactly the base layer's output.
  2. forward(x) returns base(x) + (alpha / r) * x @ A.T @ B.T, and the layer learns a low-rank change.
  3. merge() folds the update into base.weight, so inference costs nothing extra, and unmerge() takes it back out. A merged layer must not add the update a second time.
  4. add_lora(model, r, alpha, targets) wraps every nn.Linear named in targets, anywhere in a model, and freezes everything else.

As you go, tell me why B starts at zero and not A, what alpha / r buys 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:

CheckResult
numbers that train112: A holds 4 × 16, and B holds 12 × 4
numbers that stay frozen204: the base's 192 weights and 12 biases
torch.equal(lora(x), base(x)), right after wrappingTrue
the outputs after merge(), once training has moved Bthe 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.