Sub topic 4
How the LoRA update works
This chapter covers the math inside a LoRA layer and checks it in code. It assumes you know matrix multiplication and matrix rank, can read PyTorch nn.Module code, and have seen the idea from the previous chapter: a fine-tuning update can be approximated by a low-rank matrix. Choosing rank, alpha, dropout and target modules comes in the next chapter. Here we only need to know what those values do to the formula.
The core formula
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 and uses W + ΔW. LoRA does not learn ΔW directly. It writes the change as a product of two thin matrices:
W' = W + (alpha / r) · B · A| Symbol | Shape | Trained? | Role |
|---|---|---|---|
| `W` | `d_out × d_in` | No, frozen | Pretrained weight |
| `A` | `r × d_in` | Yes | Projects the input down to `r` dimensions |
| `B` | `d_out × r` | Yes | Projects back up to `d_out` dimensions |
| `r` | scalar | Fixed hyperparameter | Rank of the update |
| `alpha` | scalar | Fixed hyperparameter | Scaling numerator |
The product B·A has shape d_out × d_in, so it can be added to W. Its rank is at most r, because it is a product through an r-dimensional space. This limit on rank is the restriction that makes LoRA cheap. It also limits how much the adapter can change the layer.
Forward pass without forming ΔW
During training you never build the full B·A matrix. You compute the layer output in two branches and add them:
y = W x + (alpha / r) · B (A x)A x has only r entries per token, so the extra work is two small matrix multiplications. The frozen branch W x is unchanged. This is also why the formula is correct for any batch of inputs: the sum of the two branches equals (W + (alpha/r) B A) x by distributivity.
Parameter count
The full layer has d_out · d_in weights. The adapter has r · d_in + d_out · r = r (d_in + d_out).
For a square 4096 × 4096 projection, which is typical of a 7B-class model:
- Full weight: 4096 × 4096 = 16,777,216 values.
- Adapter at
r = 8: 8 × (4096 + 4096) = 65,536 values, about 0.39% of the full weight. - Adapter at
r = 64: 524,288 values, about 3.1%.
The count grows linearly with r. The saving comes from the fact that r (d_in + d_out) is far smaller than d_in · d_out when r is small. The optimizer state (Adam keeps two extra values per trainable parameter) shrinks by the same factor, which is a large part of the memory saving.
Initialization: why B starts at zero
The two matrices are initialized differently:
Ais filled with small random values (the original paper uses a Gaussian; PEFT uses Kaiming-uniform by default).Bis filled with zeros.
Because B = 0, the product B·A is zero, and the adapted layer starts out identical to the base layer. Training begins from the pretrained model's behavior instead of from a randomly perturbed one.
Zeroing both matrices would not work. The gradient of the loss with respect to A is proportional to B, and the gradient with respect to B is proportional to A x. If both were zero, neither would ever move. With only B at zero:
- On the first step,
Areceives zero gradient andBreceives a nonzero gradient.Bmoves away from zero. - From the second step on,
Bis nonzero, soAalso receives gradient and both matrices train.
The code below checks both claims.
Scaling by alpha / r
The factor alpha / r multiplies the adapter's contribution. Two things follow from it.
First, alpha is a knob for the adapter's strength that is separate from the learned values. With alpha = 2r, a common choice, the scale is 2.
Second, dividing by r is meant to keep the update's magnitude roughly stable as you change the rank. If you keep alpha fixed and raise r, the scale shrinks, which partly offsets the extra capacity. This is why people often tune alpha together with r and not on its own. Note that this stabilization is only approximate. A variant called rank-stabilized LoRA (rsLoRA) argues that dividing by sqrt(r) works better at high ranks. PEFT exposes it as use_rslora=True in LoraConfig.
The scale interacts with the learning rate. Doubling the scale has roughly the effect of a larger step on the adapter's contribution, so a configuration that trains well with one alpha may become unstable with another if the learning rate is unchanged.
Dropout
LoRA dropout is applied to the input of the adapter branch only, before A:
y = W x + (alpha / r) · B (A · dropout(x))The frozen branch sees the undropped input. Dropout is active only in training mode. It regularizes the small adapter against memorizing a small dataset. The minimal layer below omits it to keep the math visible.
A runnable layer
This code implements the formula, checks the parameter count, shows the gradient behavior at initialization, and verifies that a merged weight gives the same output as the two-branch forward pass.
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
torch.manual_seed(0)
layer = LoRALinear(nn.Linear(64, 64), r=4, alpha=8)
x = torch.randn(3, 64)
# 1. Trainable parameters: r * (d_in + d_out) = 4 * 128 = 512
print(sum(p.numel() for p in layer.parameters() if p.requires_grad))
# 2. With B = 0 the layer matches the base layer exactly
print(torch.allclose(layer(x), layer.base(x)))
# 3. First backward pass: A gets no gradient, B does
layer(x).sum().backward()
print(layer.A.grad.abs().max().item() == 0.0)
print(layer.B.grad.abs().max().item() > 0.0)
# 4. Pretend training moved B, then merge the update into the weight
with torch.no_grad():
layer.B.normal_(0, 0.1)
delta = layer.scale * (layer.B @ layer.A) # shape (64, 64)
merged = nn.Linear(64, 64)
merged.load_state_dict(layer.base.state_dict())
merged.weight += delta
print(torch.allclose(layer(x), merged(x), atol=1e-5))
print(torch.linalg.matrix_rank(delta).item()) # at most r = 4Expected output:
512
True
True
True
True
4The last line is the rank of the update. It is 4 and not 64 even though delta is a 64 × 64 matrix. That gap is what "low-rank" means in practice.
Merging follows from the formula
Because the update is a plain matrix added to W, you can compute W + (alpha/r) B A once and store it as a normal weight. The merged model needs no adapter code and adds no inference latency. Step 4 above is that operation in miniature, and the chapter on saving and merging uses the library version, merge_and_unload.
Merging has two consequences worth knowing now:
- It is not lossless if the base weights are stored at lower precision. Adding a small update to a weight rounded to 16-bit or 4-bit values can round away part of the update.
- It is reversible only if you keep the adapter. Once merged and saved, the update cannot be separated from
Wwithout the original base.
Where the formula is applied
LoRA is applied per layer. Each targeted nn.Linear gets its own pair A, B. In a transformer, targeting the attention projections q_proj, k_proj, v_proj and o_proj in every block gives 4 × num_layers independent low-rank updates. Layers that are not targeted stay frozen with no adapter. Embeddings and the output head are not adapted unless you ask for it. Which modules to pick is the topic of the next chapter.
Common mistakes
- Treating the adapter as a small copy of the model. It stores only
AandBfor the targeted layers. It is meaningless without the exact base weights it was trained on. - Initializing
Bto random values. The model then starts from a perturbed state, and early loss is often visibly worse than the base model's. - Forgetting that dropout touches only the adapter branch. Setting
lora_dropoutdoes not regularize the frozen weights. - Assuming a higher rank always helps. The update can represent more directions, but with a small dataset the extra capacity mostly fits noise.
Exercise
A projection layer has din = 2048 and dout = 1024. You attach LoRA with r = 16 and alpha = 32. How many trainable parameters does the adapter have, what fraction of the layer's full weight is that, and what is the scale applied to B·A?
Show answer
The adapter has r (din + dout) = 16 × (2048 + 1024) = 49,152 parameters (A is 16 × 2048 = 32,768 and B is 1024 × 16 = 16,384). The full weight has 2048 × 1024 = 2,097,152 values, so the adapter is about 2.3% of it. The scale is alpha / r = 32 / 16 = 2.
Exercise
Suppose you initialized both A and B to zero. Using the gradient formulas, explain what would happen during training.
Show answer
The gradient for A is proportional to B, and the gradient for B is proportional to A x. With both at zero, both gradients are zero on every step, so neither matrix would ever change and the adapter would stay at zero. Standard LoRA avoids this by making only B zero: A is random, so B gets a nonzero gradient on the first step, and once B is nonzero A starts receiving gradient too.
Exercise
In the code above, what does torch.linalg.matrix_rank(delta) return when delta is 64 × 64 and r = 4, and why can it not exceed 4?
Show answer
It returns 4 (for generic random values of A and B). delta equals scale · B · A, a product of a 64 × 4 matrix and a 4 × 64 matrix. Every column of the product is a combination of the 4 columns of B, so the column space has dimension at most 4, which bounds the rank by r.