Sub topic 4
How the LoRA update works
This chapter assumes you know matrix multiplication and matrix rank, and that you have run a Hugging Face transformers model for inference. You will see how LoRA changes a layer's output, why the parameter count shrinks, and how the first code example implements it.
The frozen weight and the learned update
A linear layer computes y = W x, where W has shape d_out × d_in. Full fine-tuning learns a change ΔW of the same shape, so it trains every entry of W.
LoRA freezes W and writes the change as a product of two small matrices:
W' = W + (alpha / r) · B · AAhas shaper × d_in.Bhas shaped_out × r.ris the rank, usually 4 to 64. It is far smaller thand_inandd_out.alphais a scaling constant. The update is multiplied byalpha / r.
The product B · A has the full d_out × d_in shape, but its rank is at most r. The update is therefore restricted to a low-rank subspace. This works because fine-tuning updates for a specific task tend to be low-rank in practice.
Counting parameters
Full fine-tuning of one 4096 × 4096 layer trains 16,777,216 values. LoRA with r = 8 trains 8 × 4096 + 4096 × 8 = 65,536 values, about 0.4% of the layer.
| Method | Trainable values per layer | Formula |
|---|---|---|
| Full fine-tuning | 16,777,216 | d_out · d_in |
| LoRA, r = 8 | 65,536 | r · (d_in + d_out) |
| LoRA, r = 64 | 524,288 | r · (d_in + d_out) |
The cost grows linearly with r, while the full update grows with the product d_out · d_in.
Initialization and the forward pass
A starts with small random values and B starts at zero. The product B · A is therefore zero at step 0, and the adapted layer gives the same output as the base layer. Training starts from the base model's behavior, not from a random perturbation.
If both matrices started at zero, gradients to both would be zero and nothing would learn. With only B at zero, the gradient to B is nonzero, and A begins to receive gradient once B moves away from zero.
The layer never builds the full B · A matrix. It computes the update as two thin multiplications:
y = W x + (alpha / r) · B (A x)A x has only r entries, so the extra compute is small.
The code
This is the minimal implementation. The code matches the formula above, using row-vector convention (x @ A.T @ B.T) because PyTorch batches inputs as rows.
import torch
import torch.nn as nn
class LoRALinear(nn.Module):
def __init__(self, base: nn.Linear, r: int = 8, alpha: int = 16):
super().__init__()
self.base = base
for p in self.base.parameters():
p.requires_grad_(False)
self.A = nn.Parameter(torch.randn(r, base.in_features) * 0.01)
self.B = nn.Parameter(torch.zeros(base.out_features, r))
self.scale = alpha / r
def forward(self, x):
return self.base(x) + (x @ self.A.T @ self.B.T) * self.scale
layer = LoRALinear(nn.Linear(64, 64), r=4, alpha=8)
print(sum(p.numel() for p in layer.parameters() if p.requires_grad))The script prints 512, which is 4 × 64 + 64 × 4. The base layer's 64 × 64 weight and its bias are frozen, so they are not counted.
Common errors
- Forgetting to freeze the base. If
requires_gradstaysTrueonW, you train the full layer and lose the memory savings. - Initializing
Brandomly. The adapted model then differs from the base model before any training, and early outputs can be degraded. - Mixing up shapes.
Aisr × d_inandBisd_out × r. Swapping them causes a shape error in the matmul. - Changing
rand expecting the same update size. Because of thealpha / rfactor, doublingrwith a fixedalphahalves the scale. The next chapter covers how to choose these values.
Exercise
A layer has din = 1024 and dout = 4096. You attach LoRA with r = 16 and alpha = 32. How many trainable values does the adapter add, and what is the scale applied to the update?
Show answer
A has 16 × 1024 = 16,384 values and B has 4096 × 16 = 65,536 values, so the adapter has 81,920 trainable values. The scale is alpha / r = 32 / 16 = 2.