AI Hints
Home›Fine-Tuning LLMs Tutorial›LoRA Explained
Fine-Tuning LLMs · Lesson 41 of 120

LoRA Explained

Low-rank adaptation.

⏱ 2 min read▶ Video at 1:05:44🎓 Free
Watch this lesson in the Fine-Tuning LLMs courseWatch on YouTube ↗Full Fine-Tuning LLMs course

LoRA stands for low rank adaptation. It sounds complicated, but the idea fits on one picture. Let's build it up, one piece at a time.

  • Low-Rank Adaptation
  • One picture
  • One piece at a time

The LoRA picture

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.

Why low rank?

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.

keyvalue
Rank (r)width of B and A
r = 88 columns / 8 rows
Small rankfew numbers
Big ideasimple updates are enough

LoRA in plain PyTorch

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 torch

d, r = 576, 8
W = torch.randn(d, d)                  # the frozen weight grid
B = torch.zeros(d, r)                  # LoRA matrix B starts at zero
A = torch.randn(r, d) * 0.01           # LoRA matrix A starts small and random
print(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 @ A
print("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

Summary

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.

Key takeaways
  • W frozen
  • B·A = the update
  • B starts at zero
Next up: Rank and Alpha — the two LoRA settings