All courses

LoRA: low-rank fine-tuning

Freeze W and learn the update ΔW = BA with rank r ≪ d. Compute the parameter and optimizer-memory savings, and explain why low-rank updates often suffice for fine-tuning.

Builds on: Rank and low-rank factorization, Supervised fine-tuning on demonstrations, GPU memory for training

▶ Watch this lesson Start the whole course

What the animation says

The memory wall

Fine-tuning a seven-billion-parameter model the usual way trains every weight. With mixed precision and Adam, each weight costs about sixteen bytes. The weight, its gradient, a full-precision copy, and two Adam moments. Seven billion times sixteen: about a hundred twelve gigabytes, before activations. An eighty-gigabyte GPU can't hold it. Yet does each weight really need its own update? What does chat fine-tuning mostly change?

Freeze W, add a thin side path

Mostly format and persona: a small shift. So maybe a small change is enough. Freeze every pretrained weight. Beside a chosen layer, add a small trainable side path. Its change matrix is the product of two thin factors, so its rank is at most r. Within that layer, outputs can only shift along r directions. That's often enough. The model already computes the features; fine-tuning mostly re-weights and redirects them. Absorbing lots of new knowledge is a bigger, more spread-out change, and may need a larger r.

The LoRA layer, counted

Here's the layer: X times frozen W, plus X times B times A, scaled by alpha over r. A starts at zero, so the side path adds nothing: training begins exactly at the base model. Now count. A d by d layer has d squared weights. B and A together hold just two times d times r. With d of 4096 and r of 8, that's sixty-five thousand versus nearly seventeen million. One two-hundred-fifty-sixth. Your turn: tap every matrix that gets gradients.

The bill for a 7B model

Now a real seven-billion model: width 4096, thirty-two layers. Put rank-eight LoRA on the query and value projections in every layer. Sixty-five thousand per matrix, times two, times thirty-two: about four point two million. Six hundredths of a percent. Frozen weights stay in sixteen-bit, two bytes each: fourteen gigabytes, with no gradients or Adam moments. The adapter, at sixteen bytes per parameter, is about sixty-seven megabytes. But does LoRA also remove activation memory?

Forward pass and merge

No. Backprop still flows through every frozen layer, so activations remain. In code, this line computes X times B first, then times A. That keeps everything thin: the full d by d update is never built. Since A starts at zero, this check prints True: same output as the base model. After training, merge once: add the scaled B times A into W. Same shape, same inference cost. Or keep adapters separate, and swap them per task on one shared base.

Must every weight change to fine-tune?

Full fine-tuning of a 7B model with mixed-precision Adam needs about 16 bytes per parameter, roughly 112 GB before activations. That is more than an 80 GB GPU holds. Yet SFT mostly changes format and persona, which is a small shift in behavior. Does each of 7 billion weights really need its own trainable update, gradient and optimizer state? Or can a far smaller learned change give the same result?

Freeze W, learn a thin side path

Freeze every pretrained weight. Beside a chosen linear layer, add a trainable path whose matrix $\Delta W$ is a product of two thin factors, so its rank is at most $r$. Within that layer, the update can shift outputs only along $r$ directions. Why is that often enough? The pretrained model already computes the features a task needs, and SFT mostly re-weights and redirects them. When you take the $\Delta W$ from full fine-tuning, a low-rank approximation with small $r$ captures most of it. Absorbing lots of new knowledge is a bigger, more spread-out change and may need a higher $r$.

The LoRA layer

For a frozen layer $W \in \mathbb{R}^{d_{in}\times d_{out}}$: $$Y = XW + \tfrac{\alpha}{r}\,XBA$$ Here $B \in \mathbb{R}^{d_{in}\times r}$ and $A \in \mathbb{R}^{r\times d_{out}}$ are LoRA factors, not the batch size or the attention pattern, and $r \ll d$. $A$ starts at zero, so $\Delta W = BA = 0$ and training begins exactly at the base model. The update is scaled by $\alpha/r$, where $\alpha$ is a fixed hyperparameter. Only $B$ and $A$ train: $2dr$ parameters for a $d\times d$ layer instead of $d^2$.

Savings on a 7B model

Take $d=4096$ and $L=32$. Apply LoRA with $r=8$ to the query and value projections, each $d\times d$ across all heads. - Per matrix: $2\cdot4096\cdot8=65{,}536$ - Total: $65{,}536\times2\times32\approx4.2$M params (0.06%) - Full FT: $7\text{B}\times16$ bytes $=112$ GB - LoRA: frozen bf16 weights take $7\text{B}\times2=14$ GB, with no gradients or Adam moments. The adapter takes $4.2\text{M}\times16\approx67$ MB. Activations still remain, because backprop flows through every frozen layer.

LoRA forward pass and merge

Compute $(XB)A$ in that order, so the $d\times d$ update is never built during training. After training, merge once: $W' = W + \tfrac{\alpha}{r}BA$. The layer keeps its shape, so inference costs the same as the base model. Alternatively, keep adapters separate and swap them per task on one shared base.
import numpy as np
rng = np.random.default_rng(0)
d, r, s = 512, 8, 2.0            # s = alpha / r
W = rng.normal(0, 0.02, (d, d))  # frozen, no grad
B = rng.normal(0, 0.02, (d, r))  # trainable
A = np.zeros((r, d))             # trainable, starts at 0
X = rng.normal(size=(4, d))      # 4 tokens
Y = X @ W + s * (X @ B) @ A      # never form B @ A
print(np.allclose(Y, X @ W))     # True: starts as base
print(W.size, B.size + A.size)   # 262144 8192
W_merged = W + s * B @ A         # after training: merge

Remember

LoRA freezes $W$ and trains $\Delta W = BA$ of rank $r$: $2dr$ instead of $d^2$ trainable parameters. Gradients and Adam state exist only for the adapter. Memory drops to about 2 bytes per frozen parameter, plus about 16 bytes per adapter parameter, plus activations. It works because fine-tuning usually needs only a small, low-dimensional change to features the model already has.

On Bytewise this lesson comes in small steps with a check at the end, and the app brings it back right before you would forget it.