LoRA
🪶 What is LoRA? LoRA (low-rank adaptation) fine-tunes a large model without changing its weights. Each chosen weight matrix stays frozen, and next to it the model learns two thin matrices whose product is a low-rank update. Training touches a fraction of a percent of the parameters, and after training the update can be added into the weight so inference costs nothing extra.
It comes up whenever a round turns to fine-tuning large models on limited hardware, and it is a good test of PyTorch fluency: freezing parameters, wrapping modules and proving two computations are the same.
The Prompt
LoRA is about twenty lines, so the interviewer grades the details that make it right: the initialization that leaves the model unchanged at step 0, the scaling, what is frozen, and merging without changing outputs.
"Add LoRA to a linear layer: keep the pretrained weight frozen, learn a rank-r update, and show that it trains. Then apply it to a model's layers and merge it for inference."
Clarifying Questions
You: The update is B A with A of shape (r, in) and B of shape (out, r), scaled by alpha / r?
Interviewer: Yes. Rank and alpha are arguments.
You: Should the model behave exactly like the pretrained one before training? I'd initialize B to zeros
and A randomly.
Interviewer: Yes, that's the standard.
You: Is the bias frozen too, and no dropout on the adapter input?
Interviewer: Freeze everything except the adapters. No dropout.
You: Which layers get adapters? By module name?
Interviewer: Take a list of names. In a transformer it would be the attention projections.
What You'll Build
LoRALinear(base, r, alpha): wraps a frozennn.Linear;forward(x)returnsbase(x) + scale * x A^T B^T.add_lora(model, targets, r, alpha) -> model: replaces the named linear layers in place.merge(layer) -> nn.Linear: a plain linear layer withW + scale * B A, same outputs.- A rank experiment on a task with a known low-rank change.