Here's one linear layer, with its weight grid, W. In LoRA, W stays frozen. Next to it, we add two thin grids, B and A. B is tall and thin. A is short and wide. When we multiply B by A, we get a grid the same shape as W. That's the update. Then we add the update's output to W's output. Only B and A are trained.
The number in the middle, eight here, is called the rank. It's the width of the thin grids. A small rank means few numbers to train. Low rank is the key idea. The update to W doesn't need to be complicated. It can be described with very few numbers, and still change the model's behaviour.
Let's build the pieces in plain PyTorch. W is a five hundred and seventy six by five hundred and seventy six grid. B starts as zeros. A starts with small random numbers. We count the numbers, and multiply B by A. Then we check the output for some input x. Run it. B and A have only nine thousand numbers. Less than three percent of W. Their product has the same shape as W. And because B starts at zero, the update starts at zero. So at the start of training, the model behaves exactly as before.
app.pypython
import torchd, r = 576, 8W = torch.randn(d, d) # the frozen weight gridB = torch.zeros(d, r) # LoRA matrix B starts at zeroA = torch.randn(r, d) * 0.01 # LoRA matrix A starts small and randomprint(f"Numbers in W: {W.numel():,}")print(f"Numbers in B + A: {B.numel() + A.numel():,} ({(B.numel() + A.numel()) / W.numel():.1%})")update = B @ Aprint("Update shape: ", tuple(update.shape))print("Update at start: ", update.abs().max().item())x = torch.randn(d)same = torch.allclose(W @ x + update @ x, W @ x)print("Output unchanged at start:", same)
Output
Numbers in W: 331,776
Numbers in B + A: 9,216 (2.8%)
Update shape: (576, 576)
Update at start: 0.0
Output unchanged at start: True
Let's recap. LoRA keeps W frozen, and adds two thin grids, B and A. Their product is the update. B starts at zero, so training starts from the original model. And only B and A are trained. Next, the two settings that control LoRA. Rank, and alpha.