LoRA and PEFT
LoRA trains two thin matrices beside a frozen layer. How a rank-8 update retargets a model with a fraction of a percent of the parameters.
Jump to a section
What full fine-tuning has to hold
Fine-tuning Llama 3 8B with Adam in mixed precision costs about 16 bytes per parameter before a single activation is stored: bf16 weights and gradients (2 bytes each), an fp32 master copy of the weights (4 bytes) and Adam's two fp32 moment estimates (8 bytes). For 8 billion parameters that is roughly 128 GB, more than an 80 GB GPU holds.
Most of that bill pays for the update, not the model. The frozen bf16 weights are 16 GB. The other 112 GB exist only because every weight is trainable and Adam keeps state for each one.
LoRA (low-rank adaptation) shrinks the trainable part. It freezes the pretrained weights and trains a small low-rank correction beside selected matrices. On GPT-3 175B, the original paper reports 10,000 times fewer trainable parameters and a third of the GPU memory of full fine-tuning, with quality on par with or better than full fine-tuning on the tasks it tested.
A frozen path and a trainable correction
A linear layer computes . LoRA adds a parallel branch through two small matrices: projects the input down to rank , and projects it back up.
receives no gradient. Only and train, so the change to the layer, , has rank at most . The constant sets the scale of that change and is chosen alongside the rank.
The initialization is what makes this safe to attach to a working model. starts random and starts at zero, so and the first forward pass reproduces the pretrained model exactly. On the first step 's gradient is also zero, because it flows through , but 's gradient is proportional to and is not. After one update both matrices are learning.
A small case shows the two paths. Take and a frozen layer with . At rank 2, let pick out the first two coordinates, so , and let the columns of be and . Then . With and the scale is 1, and the layer outputs .
Trace the adapter, one multiplication at a time
Keep the frozen branch in view while changing the adapter rank, scale, and initialization.
Reduced motion is on. Use Previous and Next to inspect each state.
h = Wx + (α/r)BAx r = 2, α = 0
Keep the original path
The frozen matrix maps x to [2, 1, 0]. With zero adapter scale, the output is unchanged.
Explore the inputs and calculations
Inspect A, B, and the merged weight
| 1 | 0 | 0 |
| 0 | 1 | 0 |
| 1 | 0 |
| 0 | 0.6 |
| 0 | 0 |
| 1 | 0 | 0 |
| 0 | -1 | 0 |
| 0 | 0 | 0 |
| 2 | 0 | 0 |
| 0 | -0.4 | 0 |
| 0 | 0 | 0 |
Merged output: [4, 0.4, 0]. It agrees with the two-branch calculation. This equality is for compatible dense weights, with no adapter dropout.
At B = 0, why can B learn even though A initially gets no gradient from the adapter?
The gradient for B uses Ax, which can be nonzero. The gradient for A passes through Bᵀ and is initially zero. After B changes, gradients can reach A as well.
Set back to zero and the output returns to . The adapter restricts the change to the representation, not the representation itself.
Counting what you train
Full fine-tuning trains parameters per matrix; LoRA trains . For a projection at that is parameters instead of , a factor of 256.
Llama 3 8B has 32 layers. Its query and output projections are , its key and value projections are (8 KV heads of width 128), and its three MLP matrices map between 4,096 and 14,336 dimensions. Put a rank-16 adapter on all seven projections in every layer and LoRA trains 41,943,040 parameters, about 0.5% of the model. At 16 bytes each, their weights, gradients and Adam state come to 0.67 GB, next to 16 GB of frozen weights.
1def lora_params(d, k, r):
2 return r * (d + k)
3
4# Llama 3 8B: hidden 4096, KV width 8 x 128 = 1024, MLP width 14336, 32 layers
5H, KV, FFN, LAYERS = 4096, 1024, 14336, 32
6shapes = [(H, H), (KV, H), (KV, H), (H, H), # q, k, v, o
7 (FFN, H), (FFN, H), (H, FFN)] # gate, up, down
8
9assert lora_params(4096, 4096, 8) * 256 == 4096 * 4096
10total = LAYERS * sum(lora_params(d, k, 16) for d, k in shapes)
11assert total == 41_943_040 # about 0.5% of 8B
12assert round(total * 16 / 1e9, 2) == 0.67 # GB for weights, grads and Adam stateOnce the adapter is this small, the frozen base is the largest thing left in memory. QLoRA attacks that term. It stores the base weights in a 4-bit NormalFloat format, dequantizes them to bf16 for each forward and backward pass, and computes gradients only for 16-bit LoRA adapters. The paper fine-tunes a 65B model on a single 48 GB GPU while matching 16-bit fine-tuning on its benchmarks.
Merging the adapter away
The branch is linear, so it folds into the weight it modifies:
has the same shape as . After the merge the layer is an ordinary dense matrix again, which is why the LoRA paper reports no added inference latency. Unmerged, the adapter costs two extra small matrix multiplies per adapted layer.
There are good reasons not to merge. A server that hosts many adapters on one base keeps them separate and picks one per request. A quantized base is the other case: adding a dense bf16 update to 4-bit weights means re-quantizing the sum, which gives slightly different weights from the ones the adapter was trained against. Measure quality after merging into a quantized model instead of assuming it is unchanged.
In code
A wrapper around an existing nn.Linear freezes the base and adds the two factors. The printout is the count from above, plus the base layer's bias in the total.
1import torch
2from torch import Tensor, nn
3
4
5class LoRALinear(nn.Module):
6 def __init__(self, base: nn.Linear, r: int = 8, alpha: int = 16) -> None:
7 super().__init__()
8 self.base = base
9 for p in self.base.parameters():
10 p.requires_grad_(False) # freeze the pretrained weights
11 d_out, d_in = base.weight.shape
12 self.A = nn.Parameter(torch.randn(r, d_in) * 0.01)
13 self.B = nn.Parameter(torch.zeros(d_out, r)) # B = 0 -> starts as base
14 self.scale = alpha / r
15
16 def forward(self, x: Tensor) -> Tensor:
17 return self.base(x) + self.scale * (x @ self.A.T @ self.B.T)
18
19
20layer = LoRALinear(nn.Linear(4096, 4096), r=8)
21trainable = sum(p.numel() for p in layer.parameters() if p.requires_grad)
22total = sum(p.numel() for p in layer.parameters())
23print(f"trainable {trainable:,} / {total:,} ({100*trainable/total:.2f}%)")
24# trainable 65,536 / 16,846,848 (0.39%)Where it goes wrong
Rank and scale are tangled. The update is scaled by , so raising from 8 to 16 at a fixed halves the scale. A rank sweep run that way also sweeps the effective step size of the update. Inspect the matrices and the scale separately before reading a rank comparison as a statement about capacity.
Both factors initialized to zero. Each factor's gradient passes through the other, so if and both start at zero they stay at zero. Exactly one of them should start at zero.
The base was not frozen. If the trainable count reads in billions, the optimizer is holding full state for the base and the memory savings are gone. Print the count before the first step.
The task needs more than a low-rank change. The paper found small ranks competitive on the tasks it studied, mostly with adapters on the attention query and value projections. That is evidence about those tasks, not a guarantee that every useful update is low-rank. Compare against full fine-tuning on held-out data before concluding a rank is enough.
The adapter met a different base. An adapter is tied to the exact checkpoint it was trained on. Loading it onto another revision, or merging it into a re-quantized copy, produces a model nobody evaluated.
Sources and further reading
- Hu et al., LoRA: low-rank updates, initialization, and merging.
- Dettmers et al., QLoRA: quantized frozen weights and adapter training.
- Rajbhandari et al., ZeRO (2019): the 16 bytes per parameter accounting for mixed-precision Adam.
- Llama Team, The Llama 3 Herd of Models (2024): the 8B configuration used for the counts above.
Keep going
Ask your own question about LoRA and PEFT, or start a guided session on it: six short pages, from the big picture to code you can run.