16LoRA from scratch (PyTorch)

mediumtorch
45:00

16 LoRA from scratch (PyTorch)

A prep site lists a Netflix MLE screen of rapid-fire ML fundamentals that includes LoRA (nfx-046, guide only). Anthropic's post-training posting names RLHF and Constitutional AI (1 source), and one Anthropic data scientist report had a whole interview on fine-tuning (1 report).

Four levels in solution.py. Read one level at a time and run only its tests until they pass: pytest problems/16_lora -k level1. Earlier levels must keep passing.

Level 1. LoRALinear(base, r, alpha) wraps an existing nn.Linear. The base layer is frozen, and the only trainable parts are self.A (r x in_features) and self.B (out_features x r). At creation the wrapped layer gives exactly the base layer's output, so B starts at zero and A small and random.

Level 2. forward(x) = base(x) + (alpha / r) * x @ A^T @ B^T, and the layer learns a low-rank change with Adam.

Level 3. merge() folds the scaled update into base.weight so inference costs nothing extra, and unmerge() takes it back out. A merged layer's forward must not add the update a second time. A second merge() or a second unmerge() in a row does nothing. Change base.weight in place under torch.no_grad(): a new nn.Parameter would train again.

Level 4. add_lora(model, r, alpha, targets). Anywhere inside model, replace every nn.Linear whose attribute name is in targets (the whole name: "q" matches q, not qkv) with LoRALinear(that layer, r, alpha), freeze every other parameter, and return the model. With targets=("q", "v"), every block's attn.q and attn.v get adapters, and nothing else trains.

Things to get right: why B starts at zero and not A, the alpha / r scaling and what it buys you when you change r, the parameter count (r * (in + out) versus in * out), and which layers people put LoRA on. Follow-ups: QLoRA, why merging matters for serving, and LoRA versus full fine-tuning.

solution.py
Run the tests to see which pass.