Session S19

Fine-Tuning & LoRA

A pretrained model has to be adapted to your task. What does full fine-tuning cost, how does a low-rank update cut that cost, why does the trained update cost nothing extra at inference, what does adapting make the model forget, and how far can the cheaper methods go?

Deep Learning · CS 4715/5715 · University of Idaho

HW3 is due next Monday, and Quiz 3 is next week

Before the material, where HW3, the project and Quiz 3 stand.

  • HW3 (Transformer from scratch) is due next Monday (S22) at 11:59 PM Pacific; the 12-hour grace period applies. Its generate task (greedy decoding at temperature 0, sampling otherwise) uses Wednesday's material (S20).
  • Project: the proposal, with its compute estimate, is due at the end of next week (the S23 week). If your project fine-tunes a pretrained model, today's memory arithmetic says which GPU the run fits on.
  • Quiz 3 (Module 3, S13–S22, today included) is at S23, a week from Wednesday: the last 30 minutes of class, in Canvas.

S18 pretrained a model on next-token prediction

Today adapts a model like the one S18 pretrained. From S18:

  • The objective: the average \(-\log p\) of every next token; the text supplies every label.
  • The step is S08's loop, plus S17's causal mask and a loss at every position.
  • What it costs: \(C\approx6ND\) FLOPs for \(N\) parameters and \(D\) tokens; Chinchilla's run is about 54,500 A100-days at 40% of peak.
  • What it delivered: in about three years, adapting a pretrained model became the NLP default (S19 adapts one).

S18 counted compute because pretraining's \(D\) is trillions of tokens. Fine-tuning's \(D\) is your task's data, far smaller, so the compute is affordable; what stops you is whether the training state fits in GPU memory. Today counts that memory in bytes.

Today answers five questions, from the memory cost to the limits of LoRA

Five parts, each answering one clause of the title page's question; a sixth closes.

partthe question it answers
1 · The memory costwhat does full fine-tuning cost? The bytes each trained parameter carries, worked out for a 7B model, and what that count leaves out
2 · A low-rank updatehow does a low-rank update cut that cost? The update with its shapes and its parameter count, and where its training starts
3 · LoRA from scratchwhy does the trained update cost nothing extra at inference? The class from scratch, a training run, and the check that merging changes nothing
4 · Forgettingwhat does adapting make the model forget? Three ways to adapt on a task pair with a known best loss, and what replay or removing the adapter restores
5 · The limitshow far can the cheaper methods go? LoRA's relatives, a base stored in 4 bits (QLoRA), and when full fine-tuning still wins
6 · Closecommon mistakes, today's answer, next time

Each of Parts 1–5 ends on a self-check. First, the memory cost.

In fp32 with Adam or AdamW, every trained parameter carries 16 bytes

Part 1 · The memory cost. Fine-tuning continues gradient descent on your task's data: S11's transfer learning, now on a pretrained language model. The method is full fine-tuning, supervised fine-tuning (SFT) with every weight trainable: S08's training loop with AdamW, on your task's labeled data (for a language model, the same next-token loss, on the task's text). Part 1 prices this method; LoRA, later today, is its alternative. Trained with fp32 and Adam or AdamW (S06), every trainable parameter carries:

fp32 + Adam/AdamWweight 4 Bgradient 4 BAdam m 4 BAdam v 4 B= 16 bytesOne cell is one byte per trainable parameter.
  • Adam's \(m\) and \(v\) are its running means of the gradients and of their squares (S06).
  • Every number is kept in full precision, and the computation and the update both run in fp32: the simplest setup, but also the slowest.

The training state is about four times the fp32 weights, before a single activation.

Mixed precision computes in bf16 but pays 16 bytes per trained parameter

weightgradientmixed precisionbf16 2 Bbf16 2 Bfp32 master 4 BAdam m 4 BAdam v 4 B= 16 bytesOne cell is one byte per trainable parameter. bf16 is S18's 16-bit float format.
  • Why compute in bf16: matrix multiplications run much faster (S18's A100 peak, \(312\times10^{12}\) FLOP/s, is its bf16 peak), and activations stored in bf16 take half the memory.
  • Why an fp32 master copy: just above 1, bf16 numbers are about 0.0078 apart, so in bf16 \(1.0+0.001\) is still \(1.0\): the update is rounded away. A learning rate times a gradient is usually far smaller than the weight, so the fp32 copy is updated, then cast back to bf16.
  • 16 bytes is a planning recipe for these setups, not a constant: some optimizers keep 8-bit moments, shard the states, or allocate them lazily (reading 3.6).

Mixed precision saves time and activation memory, not training state: both layouts cost 16 bytes.

Training memory is 16 bytes per trained parameter and 2 per frozen one

Two ways to fine-tune a model with \(N\) parameters. The second, LoRA, previews Part 2: freeze the pretrained weights, train about 0.1%.

  • Full fine-tuning trains all \(N\) parameters. LoRA trains about 0.1% of them, \(0.001N\): reading 3.6's typical budget (Part 2 shows where the ratio comes from).
  • A trained parameter carries the 16 bytes of the previous two pages. A frozen one, stored in bf16, carries only its 2-byte weight: no gradient, no optimizer state, no fp32 master copy.

In GiB (\(1024^3\) bytes), before activations (reading 3.6 has the script):

\[\begin{aligned}\text{full fine-tuning:}&\quad N\cdot16/1024^3\\ \text{LoRA, frozen base:}&\quad (N\cdot2+0.001N\cdot16)/1024^3\end{aligned}\]

Predict for 7B: GiB for full fine-tuning, and with the frozen base.

A 7B model needs 104 GiB to fine-tune in full, 13 GiB with a frozen base

Answer: \(7\times10^9\times16\) bytes is 104.3 GiB; with the base frozen, 13.1. The same formulas on popular models, in GiB before activations; cards by their memory in GB (24 GB: a consumer RTX 4090; 80 GB: an A100 or H100):

modelparametersfull fine-tuning, GiBneedsLoRA, frozen base, GiBneeds
GPT-2 small (S18)124M1.8one 24 GB card0.2one 24 GB card
7B, the prediction7.0B104.3two 80 GB cards13.1one 24 GB card
Mistral 7B7.2B107.3two 80 GB cards13.5one 24 GB card
Llama 3.1 8B8.0B119.2two 80 GB cards15.0one 24 GB card
Llama 3.1 70B70.6B1052.0fourteen 80 GB cards132.6two 80 GB cards
  • The fp32 weights alone, \(7\times10^9\times4\) bytes, are 26.1 GiB and fit a high-end GPU; the training state does not. "I can run inference on it" does not imply "I can fine-tune it".

What LoRA buys: an 8B model needs about 119 GiB to fine-tune in full, two 80 GB cards; with the base frozen, about 15 GiB, one 24 GB consumer card, before activations.

The table leaves out two costs: activations, and one full model per task

The table counts weights and training state only (reading 3.6).

(1) Activations. They come on top and grow with batch size and sequence length. LoRA does not substantially reduce the activations saved through the frozen network, so long sequences can still dominate memory.

full fine-tuningtraining state, in the tableactivationsLoRAactivations, about the sameSolid: the table's 104.3 and 13.1 GiB for 7B, to scale. Dashed: activations, not to scale.

(2) A full model per task. Full fine-tuning produces a complete copy of the model for every task. Ten fine-tuned 7B variants are about 260 GiB of nearly identical checkpoints:

full fine-tuning7B7B7B7B7B7B7B7B7B7B260 GiB

What today cuts is the training state and the full model per task: LoRA saves both, and Part 3 returns to the second.

Self-check on a 3B model's memory, with and without a frozen base

Three questions on Part 1 (\(1\ \text{GiB}=1024^3\) bytes).

(a) A 3B model, fine-tuned in full with AdamW in fp32: its training state before activations, in GiB?

(b) The same model with its base frozen in bf16 and 0.1% of the parameters trained at 16 bytes?

(c) After the switch to LoRA, a run at sequence length 8,192 still runs out of memory. What is left, and what helps?

(a) \(3\times10^9\cdot16/1024^3\approx44.7\) GiB.

(b) \(3\times10^9\cdot2\) bytes for the base plus \(3\times10^6\cdot16\) for the trained 0.1%: about 5.6 GiB.

(c) The activations: LoRA does not substantially reduce them, and they grow with sequence length. Shorter sequences or a smaller batch help.

That settles the memory cost. Next comes Part 2, training far fewer parameters.

LoRA freezes \(W\) and trains a low-rank update \(\tfrac{\alpha}{r}BA\)

Part 2 · A low-rank update. LoRA (Low-Rank Adaptation, Hu et al., 2021) rests on a hypothesis inspired by Aghajanyan et al. (2021): fine-tuning's weight changes have low rank. So train only a change to each \(W\) (\(d_{\text{out}}\times d_{\text{in}}\)):

\[W'=W+\frac{\alpha}{r}\,BA,\qquad A:\ r\times d_{\text{in}},\qquad B:\ d_{\text{out}}\times r\]
Wfrozendoutdin+α/rBrAdinrBAsame shape as Wrank rFor a 4096 × 4096 projectionand r = 8, W holds 16.8Mentries; B and A togetherhold 65,536 (0.4%).Hatched: frozen. Orange: trained. B and A are drawn wider than scale.
  • \(W\) stays frozen; only \(A\) and \(B\) train (\(\alpha\) is a constant you set, not trained), with \(r\) from 1 to 64 in the paper.

A rank-\(r\) update is a sum of \(r\) outer products

What a low rank limits, first with \(r=1\):

\[B=\begin{bmatrix}1\\2\end{bmatrix},\quad A=\begin{bmatrix}1&0&-1\end{bmatrix}:\qquad BA=\begin{bmatrix}1&0&-1\\2&0&-2\end{bmatrix}\]
  • Every row of \(BA\) is a multiple of \(A\)'s one row: rank 1. With columns \(b_j\) of \(B\) and rows \(a_j^{\top}\) of \(A\), \(BA=\sum_{j=1}^{r}b_j\,a_j^{\top}\): each term, a column times a row (an outer product), has rank 1, so \(BA\) has rank at most \(r\).

Only the correction is constrained to be simple; the pretrained \(W\) stays as rich as it was.

A rank-\(r\) update changes the layer along \(r\) input directions only

On an input, \(BAx=B(Ax)\): \(Ax\) holds \(r\) numbers, one per row of \(A\). The previous page's \(r=1\) update, on two inputs:

\[B=\begin{bmatrix}1\\2\end{bmatrix},\qquad A=\begin{bmatrix}1&0&-1\end{bmatrix}\]
  • \(x=(1,0,1)\): \(Ax=0\), so \(BAx=0\) and the layer outputs \(Wx\), as before.
  • \(x=(1,0,0)\): \(Ax=1\), so \(BAx=(1,2)\) and the output changes.
  • A rank-1 update changes the layer along one input direction only; rank \(r\), along \(r\) directions.
  • Reading 3.6: an update of rank 8 maps 8 directions of input to 8 directions of output; everything else the layer does passes through unchanged.

LoRA trains \(r(d_{\text{in}}+d_{\text{out}})\) parameters instead of \(d_{\text{out}}\,d_{\text{in}}\)

\(A\) holds \(r\,d_{\text{in}}\) numbers and \(B\) holds \(d_{\text{out}}\,r\); a dense update trains all \(d_{\text{out}}\,d_{\text{in}}\) entries. A \(4096\times4096\) attention projection with \(r=8\):

  1. LoRA: \(8\cdot(4096+4096)=65{,}536\) trainable parameters.
  2. Dense: \(4096^2=16{,}777{,}216\), about 16.8 million.
  3. Ratio: \(65{,}536/16{,}777{,}216\approx0.39\%\), the reading's 0.4%.

In general the ratio is

\[\frac{r\,(d_{\text{in}}+d_{\text{out}})}{d_{\text{in}}\,d_{\text{out}}}=r\left(\frac{1}{d_{\text{out}}}+\frac{1}{d_{\text{in}}}\right),\]

so it falls as the layer widens: at \(4096\times4096\), \(r=4\) gives 0.2%.

Only these parameters cost Part 1's 16 bytes each; the frozen \(W\) costs 2 per entry in bf16.

With \(B=0\) at initialization, training starts at the pretrained model

The first of three design details (reading 3.6).

  • Initialization: \(A\) is small Gaussian noise and \(B\) is zeros, so \(BA=0\): at step 0 the layer computes exactly \(Wx\), the pretrained output.

What does the layer compute at step 0 if both \(A\) and \(B\) are zero? If both are random?

Both zero: exactly \(Wx\), but nothing trains: \(B\)'s gradient carries the factor \(Ax = 0\) and \(A\)'s the factor \(B = 0\), so neither ever moves.

Both random: \(Wx + \frac{\alpha}{r}BAx\), the pretrained layer plus noise.

\(A\) random and \(B = 0\) gets both right: \(Wx\) at step 0, and \(B\)'s gradient is nonzero because \(Ax \neq 0\).

By S05's rules, the LoRA gradients are \(dB=s\,dY^{\top}H\) and \(dA=dH^{\top}X\)

For a batch \(X\) (\(N\times d_{\text{in}}\)) the code computes \(H=XA^{\top}\) (\(N\times r\)), then the update's output \(Y=s\,HB^{\top}\) (\(N\times d_{\text{out}}\)), with \(s=\alpha/r\). S05's rules for \(Z=XW\): \(dW=X^{\top}dZ\), \(dX=dZ\,W^{\top}\); here \(dY=\partial L/\partial Y\):

\[\begin{aligned}Y=H\,(sB^{\top}):&\quad d(B^{\top})=H^{\top}(s\,dY),\ \text{so}\ dB=s\,dY^{\top}H;\\ &\quad dH=s\,dY\,B\\ H=X\,A^{\top}:&\quad d(A^{\top})=X^{\top}dH,\ \text{so}\ dA=dH^{\top}X\end{aligned}\]
  • Shapes: \(dB\) is \(d_{\text{out}}\times r\) like \(B\), \(dH\) is \(N\times r\), \(dA\) is \(r\times d_{\text{in}}\) like \(A\).

Each gradient carries the other factor: \(dB\) through \(H=XA^{\top}\), \(dA\) through \(dH=s\,dY\,B\).

So one factor must start nonzero: with \(B=0\) both train, with \(A=B=0\) neither moves

at step 0\(H=XA^{\top}\)\(dB=s\,dY^{\top}H\)\(dA=dH^{\top}X\)trains?
\(A\) random, \(B=0\)\(H\neq0\)\(dB\neq0\)\(dA=0\)yes: after one step \(B\neq0\), and \(A\) trains too
\(A=B=0\)\(H=0\)\(dB=0\)\(dA=0\)no: neither ever moves
\(A\), \(B\) random\(H\neq0\)\(dB\neq0\)\(dA\neq0\)yes, but from \(W\) plus noise
  • Recorded run on reading 3.6's two-layer model, with \(B=0\): at step 0 the largest entry of \(|dA|\) is 0 and of \(|dB|\) 4.4e-03.
  • With both zero, \(A\) and \(B\) are still all zero after 200 AdamW steps, the loss still 2.3034.

With \(B=0\) training starts at the pretrained model and still moves; with both zero it never leaves it.

Design details 2 and 3 are the scale \(\alpha/r\) and where the updates go

  • Scale \(\alpha/r\): \(\alpha\) is a constant you choose once (Part 3's class uses \(\alpha=8\) with \(r=4\), a scale of 2); dividing by \(r\) decouples the update's magnitude from the rank, so changing \(r\) does not force retuning the learning rate (the paper's stated motivation).
xWqBAWkBAWvBAattentionWoBAattention sublayerFFN: two linear layerslinearBAlinearBAThe paper adapted Wq and Wv and reported that this sufficed.Later practice often adapts every linear layer. Hatched boxes are frozen.
  • The paper's reported payoff on GPT-3 175B: about 10,000 times fewer trainable parameters, about 3 times less GPU memory in training, and quality on par with, sometimes better than, full fine-tuning on their benchmarks.
  • Those are the paper's numbers on its setup, not a universal law: tasks far from the pretraining distribution can defeat low rank, and \(r\) is a hyperparameter you tune (Part 5).

Self-check on the parameter count, the zero gradient and the rank

Three questions on Part 2.

(a) An FFN layer maps \(d_{\text{in}}=4096\) to \(d_{\text{out}}=16{,}384\) (S16's \(4d\)). A rank-8 update: how many trainable parameters, and what fraction of \(W\)'s entries?

(b) \(A\) small and random, \(B=0\). At step 0, which gradient is zero, and why does that factor still train?

(c) With \(r=8\), can \(BA\) have rank 9?

(a) \(8\cdot(4096+16{,}384)=163{,}840\) against \(67{,}108{,}864\): about 0.24%.

(b) \(dA\), which carries the factor \(B=0\). \(dB\neq0\), so \(B\) moves at the first step, and from then on \(dA\neq0\).

(c) No: \(BA\) is a sum of 8 rank-1 matrices, so its rank is at most 8.

That settles the low-rank update. Next comes Part 3, which writes it, trains it and merges it.

Part 3 trains only a rank-4 update beside each frozen layer

Part 3 · LoRA from scratch. First the whole model, reading 3.6's small network, then the code that builds it.

x64model[0]Linear 64 → 128Ar = 4Bfrozen 8,320 · LoRA 768ReLUmodel[2]Linear 128 → 10Ar = 4Bfrozen 1,290 · LoRA 552logits10Each Linear gets its own A and B, rank r = 4.

Orange is trained and hatched is frozen. The next pages write the class (p21), wrap one layer (p22), then build this model (p23).

LoRA from scratch wraps a frozen nn.Linear and adds the low-rank path

Reading 3.6's class, after its imports (import torch, import torch.nn as nn):


class LoRALinear(nn.Module):
    """A frozen nn.Linear plus a trainable low-rank update (alpha/r) * B @ A."""
    def __init__(self, base: nn.Linear, r=4, alpha=8):
        super().__init__()
        self.base = base
        for p in self.base.parameters():
            p.requires_grad = False          # freeze W and bias
        self.r, self.alpha = r, alpha
        self.A = nn.Parameter(torch.randn(r, base.in_features) * 0.01)
        self.B = nn.Parameter(torch.zeros(base.out_features, r))

    def forward(self, x):
        return self.base(x) + (self.alpha / self.r) * (x @ self.A.T @ self.B.T)

    def merged_weight(self):
        return self.base.weight + (self.alpha / self.r) * (self.B @ self.A)
  
  • x @ self.A.T @ self.B.T: (N, d_in) → (N, r) → (N, d_out). merged_weight: \(W+\frac{\alpha}{r}BA\), (d_out, d_in).

A wrapped layer prints its shapes and count, and equals the base at step 0

The previous page's class on a 64-to-128 layer and a batch of 512 inputs:


layer = LoRALinear(nn.Linear(64, 128), r=4, alpha=8)   # d_in = 64, d_out = 128
x = torch.randn(512, 64)                               # a batch of N = 512 inputs
print(layer.A.shape, layer.B.shape)                    # (r, d_in), (d_out, r)
print((x @ layer.A.T).shape, layer(x).shape)           # (N, r), (N, d_out)
print(sum(p.numel() for p in layer.parameters() if p.requires_grad))
print(torch.equal(layer(x), layer.base(x)))            # B = 0: the frozen layer exactly
  

torch.Size([4, 64]) torch.Size([128, 4])
torch.Size([512, 4]) torch.Size([512, 128])
768
True
  
  • 768 trainable: \(r(d_{\text{in}}+d_{\text{out}})=4\cdot(64+128)\). The frozen weight and bias hold \(64\cdot128+128=8{,}320\).
  • torch.equal tests exact equality: with \(B=0\) the wrapped layer returns the frozen layer's output bit for bit. Reading 3.6 recommends this check before training.

Reading 3.6's model wraps two layers. What fraction of it trains?

A small network whose random weights stand in for pretrained ones; both of its nn.Linear layers get a rank-4 update:


torch.manual_seed(0)                    # the reading's seed, set before its class
d_in, d_hidden, d_out = 64, 128, 10
model = nn.Sequential(nn.Linear(d_in, d_hidden), nn.ReLU(),
                      nn.Linear(d_hidden, d_out))
# pretend this model is pretrained; wrap both Linears with LoRA
model[0] = LoRALinear(model[0], r=4, alpha=8)
model[2] = LoRALinear(model[2], r=4, alpha=8)

total = sum(p.numel() for p in model.parameters())
trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
print(f"total params    : {total:,}")
print(f"trainable (LoRA): {trainable:,} ({100 * trainable / total:.2f}%)")
  

Two layers, \(r = 4\), 10,930 parameters in all. Predict the trainable fraction: about 0.1%?

12.08% of the model trains, not 0.1%, because these layers are narrow

Answer: no. The first two printed lines, and where they come from:


total params    : 10,930
trainable (LoRA): 1,320 (12.08%)
  
layer\(d_{\text{in}}\to d_{\text{out}}\)frozen, weight + biasLoRA, \(r(d_{\text{in}}+d_{\text{out}})\)LoRA / \(W\)'s entries
model[0]64 → 1288,320768768 / 8,192 = 9.4%
model[2]128 → 101,290552552 / 1,280 = 43.1%
both9,6101,3201,320 / 10,930 = 12.08% of all
  • Part 2's ratio \(r(1/d_{\text{out}}+1/d_{\text{in}})\) is large on narrow layers. At \(4096\times4096\) the same \(r=4\) gives 0.2%: parameter efficiency is a big-model phenomenon (reading 3.6).

From chance to 100% training accuracy in 200 steps, training only \(A\) and \(B\)

Train p23's model, whose two nn.Linear layers are frozen, on a synthetic 10-class task (F is torch.nn.functional); the optimizer gets only \(A\) and \(B\), the 1,320 parameters that require gradients:


# synthetic classification task
g = torch.Generator().manual_seed(1)
X = torch.randn(512, d_in, generator=g)
w_true = torch.randn(d_in, d_out, generator=g)
y = (X @ w_true).argmax(dim=1)

opt = torch.optim.AdamW([p for p in model.parameters() if p.requires_grad], lr=1e-2)
for step in range(201):
    loss = F.cross_entropy(model(X), y)
    opt.zero_grad(); loss.backward(); opt.step()
    if step % 100 == 0:
        acc = (model(X).argmax(1) == y).float().mean()
        print(f"step {step:3d}  loss {loss.item():.4f}  acc {acc.item():.4f}")
  

step   0  loss 2.3034  acc 0.0977
step 100  loss 0.0492  acc 1.0000
step 200  loss 0.0058  acc 1.0000
  
  • Step 0's loss 2.3034 is about \(\ln10\approx2.3026\), chance for 10 classes: with \(B=0\), the model is still the frozen network.
  • The frozen network is random, standing in for a pretrained one; two rank-4 updates, 1,320 parameters, fit this task.

The merge check folds \(\tfrac{\alpha}{r}BA\) into a plain nn.Linear and compares

After training, copy \(W+\frac{\alpha}{r}BA\) and the bias into an unwrapped network, and compare the two on fresh inputs:


with torch.no_grad():
    merged = nn.Sequential(nn.Linear(d_in, d_hidden), nn.ReLU(),
                           nn.Linear(d_hidden, d_out))
    for i in (0, 2):
        merged[i].weight.copy_(model[i].merged_weight())
        merged[i].bias.copy_(model[i].base.bias)
    x_test = torch.randn(64, d_in, generator=g)
    diff = (model(x_test) - merged(x_test)).abs().max()
print(f"max |LoRA model - merged model| on fresh inputs: {diff.item():.2e}")
  

max |LoRA model - merged model| on fresh inputs: 2.34e-05
  
  • 2.34e-05 is fp32 round-off, not a bug: the wrapped layer computes \((xA^{\top})B^{\top}\), the merged one \(x(BA)^{\top}\). The linear map is the same; the rounding differs.
  • So compare with a tolerance (torch.allclose with a sensible atol), not torch.equal.

The merge property gives one matrix at inference

  • \(y = Wx + \frac{\alpha}{r}B(Ax) = \big(W + \frac{\alpha}{r}BA\big)x\): the same linear map in two associations.
adapter attachedmergedxdinWWxArBα/r · B(Ax)ydoutfoldunmergexdinW + α/r · BAydoutone matrix, no extra moduleUnmerging subtracts α/r · BA again: the base returns exactly, up to round-off.
  • Merged, zero additional inference latency; an unmerged adapter still runs its low-rank path. Adapter layers (Houlsby et al., 2019; Part 5) run at serving time.

One frozen base can serve many tasks, each with its own small adapter

Why many adapters: one base usually serves several tasks, each fine-tuned on its own data (p9's ten variants), and fine-tuning one model on them in turn forgets the earlier ones (Part 4).

With LoRA the base never changes, so each task keeps only its \(A\) and \(B\), and unmerging switches the base between tasks:

full fine-tuning7B7B7B7B7B7B7B7B7B7B260 GiB (Part 1)LoRA7Bone 26 GiB base; swap tasks by swapping adaptersEach adapter is kilobytes to megabytes, so the orange strips are drawn far larger than scale.
  • The merge property, with a simple implementation, made LoRA the default within about two years.

Self-check on an unmerged adapter, a small difference and the way back

Three questions on Part 3.

(a) A \(4096\times4096\) layer with an unmerged rank-8 adapter: extra multiply-adds per input for \(B(Ax)\), against \(Wx\)?

(b) Merged and wrapped logits differ by 3e-05 in fp32. A bug?

(c) You merged an adapter into \(W\). How do you get the base back?

(a) \(8\cdot4096+4096\cdot8=65{,}536\), against \(4096^2=16{,}777{,}216\): 0.4% more. Merged, none.

(b) No: round-off from the other association order. Compare with a tolerance.

(c) Subtract \(\frac{\alpha}{r}BA\) from the merged weight; exact up to round-off.

That settles LoRA from scratch. Next comes Part 4, what adapting makes the model forget.

The task pair is a cycle and its reverse, with a known best loss

Part 4 · Forgetting. Reading 3.6 generates its training data from two Markov chains over a, b, c, d (the next symbol depends only on the current one); a small Transformer learns them by predicting the next symbol, as in S18:

language A: a → b → c → d → aabcd0.90.90.90.9language B: a → d → c → b → aabcd0.90.90.90.9Each arrow is followed with probability 0.9; each of the other three symbols gets 0.1/3.
  • The chains are known, so the best possible loss is their entropy, in nats per token: \(H=-\big(0.9\ln0.9+3\cdot\tfrac{0.1}{3}\ln\tfrac{0.1}{3}\big)=0.0948+0.3401\approx0.4349\). Uniform guessing: \(\ln4\approx1.386\).
  • The learner: a one-block Transformer (width 32, context 16, 13,476 parameters), pretrained on A for 300 steps, then adapted to B (next page).

To do well on B, the model must change how it maps each symbol to the next.

The learner is one Transformer block between an embedding and a head

4 logits for the next symbolhead 32 → 4up 32 → 128GELUdown 128 → 32LayerNormo 32 → 32attention (causal mask)qkvBABA32 → 32 eachLayerNorm8 virtual tokensembedding + position (width 32)abcda…up to 16 symbolsFull fine-tuning trainsevery module in the bracket.BALoRA (r = 4) trains onlyA and B beside q and v.Prompt tuning trains onlythe 8 vectors before the input.With LoRA or prompt tuning,every module is frozen.

The three methods train different parts of the same model.

Of three ways to adapt to B, LoRA comes close to full fine-tuning

Reading 3.6, same 300-step budget: full fine-tuning updates every weight; LoRA wraps \(W_q\) and \(W_v\) with \(r=4\); prompt tuning (Lester et al., 2021) freezes every weight, including the embedding table, and trains 8 extra input vectors ("virtual tokens", not words in the vocabulary) prepended to every sequence; the model reads them as context. Part 5 places all three in the PEFT (parameter-efficient fine-tuning) family.


entropy floor of either language: 0.4349 nats/token
after pretraining: loss on A = 0.4479

                method  trainable  loss on B
         no adaptation          0     3.2663
        full fine-tune     13,476     0.4329
       LoRA (r=4, q+v)        512     0.4511
 prompt tuning (8 tok)        256     3.1260
  
  • No adaptation, 3.2663: above uniform's 1.386, since the model confidently predicts the forward cycle. Full, 0.4329: at the floor (slightly below it: noise of the finite validation set).
  • LoRA, 0.4511 with 512 parameters, 3.8% of the model: this task's update is expressible at rank 4. Prompt tuning, 3.1260: virtual tokens add context, but cannot change how the frozen model maps its last token to the next.

Fine-tune on B, then test on A, with replay and with a removable adapter

Reading 3.6's second script (same pair, model, loop; report prints the loss on A and on B). After full fine-tuning on B, two more ways; replay mixes some original data back in, and Part 3's LoRALinear wraps q and v (p31's figure):


replay = copy.deepcopy(base)
mixed = torch.cat([task_B[:1600], task_A[:178]])   # ~10% A
train(replay, mixed, replay.parameters())
report("full FT on B + 10% A replay", replay)

lora = copy.deepcopy(base)
for p in lora.parameters():
    p.requires_grad = False
q_base, v_base = lora.q, lora.v                    # keep handles to the originals
lora.q, lora.v = LoRALinear(q_base), LoRALinear(v_base)
train(lora, task_B[:1600], [p for p in lora.parameters() if p.requires_grad])
report("LoRA on B (adapter attached)", lora)

lora.q, lora.v = q_base, v_base                    # swap the adapter back out
report("LoRA on B (adapter removed)", lora)
  

Predict the loss on A, low or high: full fine-tuning on B; with 10% A mixed in; LoRA attached; LoRA removed.

What LoRA does not buy is protection from forgetting

The printout for the task pair (pretrained on A, adapted to B), loss in nats per token:


                             model    loss A    loss B   (floor 0.4349)
                   pretrained on A    0.4479    3.2663
                      full FT on B    3.4150    0.4329
       full FT on B + 10% A replay    0.9034    0.4754
      LoRA on B (adapter attached)    3.6655    0.6290
       LoRA on B (adapter removed)    0.4479    3.2663
  
loss on Aloss on Bpretrainedfull FT+ replayLoRA attachedLoRA removedCatastrophic forgetting:B's loss never mentions AReplay (~10% A data mixed in) brings most of A backLoRA attached forgets A as badly;removed, the base returns exactly:reversibility, not immunityBar lengths are the losses printed above; the dashed lines mark the floor.

Each row has a cause, and LoRA's rows show reversibility, not immunity

  • Catastrophic forgetting (McCloskey and Cohen, 1989): B's loss never mentions A, so gradient descent on B has no reason to keep A. Full fine-tuning takes A from 0.4479 to 3.4150.
  • Replay: 178 A sequences among 1,778 (10.0%) bring A back to 0.9034 at a small cost on B (0.4754). Real post-training pipelines mix pretraining data in for this reason.
  • LoRA attached, 3.6655 on A: its 512 parameters sit in \(W_q\) and \(W_v\), in the middle of the computation.
  • LoRA removed: exactly the pretrained row; the frozen weights never moved (bit-identical logits, recorded run).
  • LoRA's 0.6290 on B is not the three-way run's 0.4511: the replay run comes first, so LoRA gets other random draws. Its row is the one that moves with the draws.

One frozen base plus one small adapter per task serves every task without interference.

Self-check on forgetting, replay and adapters

Three questions on Part 4.

(a) After full fine-tuning on B, the loss on A is 3.4150, above uniform's 1.386. Why?

(b) A and B must both be served from one base, without interference. Replay, or one adapter per task?

(c) Does training only 512 of 13,476 parameters protect A while the adapter is attached?

(a) It now predicts B's cycle. At nine positions in ten, A's next symbol gets about B's \(0.1/3\), and \(-\ln(0.1/3)\approx3.40\).

(b) One adapter per task: removing it restores the base exactly. Replay trades A against B.

(c) No: 3.6655 on A. They change \(W_q\) and \(W_v\), and with them every position's attention.

That settles forgetting. Next comes Part 5, on LoRA's relatives, a 4-bit base and the limits.

The PEFT methods differ in where the trained correction lives

Part 5 · The limits. PEFT (parameter-efficient fine-tuning): hold the pretrained function fixed and learn a small, structured correction. Where it lives decides what it can express and whether it disappears at serving time.

In the token stream:prompt tuning (Lester et al., 2021)and prefix tuning (Li & Liang, 2021)abclearned virtual-tokenembeddings before the input;every weight frozenParallel to W: LoRAmerges into W, no added latencyxWABQLoRA (Dettmers et al., 2023):same correction, frozen basestored in 4 bits (NF4)xABIn series, between sublayers:adapters (Houlsby et al., 2019)hσnonlinearityd → mm → da small bottleneck MLP after eachattention and FFN sublayer; thenonlinearity keeps it from foldinginto W, so it runs at serving timeorange: trainedhatched: frozenThree places for the correction; each method is applied across the whole model.
  • On standard benchmarks the methods often land within a point or two of each other (Part 4's tiny model is far from that scale); which one wins varies by task and scale, so treat published rankings as evidence about a setting, not a verdict. The merge property and a simple implementation, not raw quality, made LoRA the default.

Storing a weight in 4 bits means one of 16 levels times a scale shared by its block

Store, once per block…64 weights÷ scalescale = thelargest |w|−1116 levelseach weight goes to the nearest level…scale64 level numbers,4 bits each, + 1 scaleBefore each matmul…level× scaleW16-bit, ≈ the originalWxABThe gradient passes through Winto A and B; the stored codesand scales never change.
  • Per weight, 4 bits are 0.5 bytes; each block of 64 weights adds one scale.
  • S26 returns to quantization for serving.

QLoRA stores the frozen base in 4 bits and trains LoRA adapters on top

QLoRA is LoRA's 4-bit variant from the map. After LoRA, the largest term is the frozen base, 2 bytes per parameter in bf16. Dettmers et al. (2023) store it in 4 bits (previous page) and dequantize it for each matmul; the gradient flows through it into higher-precision adapters.

  • NF4 (NormalFloat-4) places the 16 levels at the quantiles of a normal distribution, since trained weights are roughly Gaussian.
  • Double quantization: an fp32 scale per 64-weight block would add 0.5 bits per parameter, so the scales are quantized too.
  • Paged optimizer states: Adam's buffers move to CPU memory when a batch spikes.

Reading 3.6's arithmetic, in Part 1's GiB (GiB = 1024 ** 3); a model "fits" a GPU when qlora(n) is under 85% of its memory, to leave room for activations:


def qlora(n, frac=0.001):
    base = 0.5 * n            # NF4: 4 bits per weight
    scales = n / 64 * 1       # one 8-bit quantized scale per 64-weight block
    return (base + scales + 16 * frac * n) / GiB

gpus = [("RTX 4090", 24), ("A6000", 48), ("A100/H100", 80)]
  

QLoRA fits a 65B model in about 32 GiB before activations

The script's printout (its printing loop, over five model sizes, is not shown):


 model     full FT      LoRA     QLoRA   fits on (QLoRA)
  1.3B     19.4GiB    2.4GiB    0.6GiB   RTX 4090, A6000, A100/H100
    7B    104.3GiB   13.1GiB    3.5GiB   RTX 4090, A6000, A100/H100
   13B    193.7GiB   24.4GiB    6.4GiB   RTX 4090, A6000, A100/H100
   33B    491.7GiB   62.0GiB   16.3GiB   RTX 4090, A6000, A100/H100
   65B    968.6GiB  122.0GiB   32.2GiB   A6000, A100/H100

65B breakdown under QLoRA:
  4-bit frozen base        :   30.3 GiB
  quantization scales      :    0.9 GiB
  LoRA params + grads+Adam :    1.0 GiB
  total (no activations)   :   32.2 GiB
  
  • For 65B, full, LoRA, QLoRA: 969, 122, 32 GiB. Plus activations, that is how the paper's claim comes out: a 65B model fine-tuned on a single 48 GB GPU.
  • Not removed: activations still grow with batch and sequence length; dequantizing on the fly makes each step somewhat slower. The 4-bit format is a storage format, not a training precision.

Full fine-tuning still wins when the update is not low-rank

The low-rank hypothesis is about adapting within the pretrained distribution: style, format, task framing, vocabulary the model has partly seen (reading 3.6).

choose full fine-tuning whenchoose LoRA when
the update must be high-rank: a new language with an unfamiliar script, a domain absent from pretraining, continued pretraining on billions of new tokensyou are adapting the model, not teaching it a new domain: style, format, task framing
target-domain capability is everything, and you have the data and hardwarekeeping general ability or swapping tasks cheaply is the point; or you have a few hundred examples, where full fine-tuning mostly buys overfitting
  • Biderman et al. (2024), "LoRA Learns Less and Forgets Less": on code and math, full fine-tuning learns the target domain better, most visibly in continued pretraining on code; LoRA degrades the source-domain abilities less. Part 4's task pair is the opposite case: there, learning B means unlearning A, and LoRA attached forgot A as badly (3.6655).

Self-check on QLoRA, a format task and the cost at serving time

Three questions on Part 5.

(a) QLoRA's table: 3.5 GiB for 7B. Which term is most of it, and what does a long context still cost?

(b) Your project teaches a model to always answer in one fixed format, from 500 examples. Full fine-tuning or LoRA?

(c) Merged LoRA, adapter layers, prompt tuning: which add computation at serving time?

(a) The 4-bit base, \(0.5\cdot7\times10^9\) bytes, about 3.3 GiB. Activations, which QLoRA does not shrink.

(b) LoRA: a format is adaptation within the distribution, and with few examples the constraint helps.

(c) Adapter layers (in series) and prompt tuning (extra tokens in every input). Merged LoRA adds nothing.

That settles the limits. Next comes the close.

Six mistakes in your own fine-tuning runs, each with its cause and its fix

Part 6 · Close. Reading 3.6's pitfalls, and its caution about libraries:

symptomcausefix
out of memory, though the checkpoint fits the GPU easily16 bytes per trained parameter, plus activationsdo the arithmetic first; freeze what you can; shorter sequences or batches
an early loss spike, pretrained quality never recovered\(B\) random at a layer's usual scale instead of zeros: training starts at \(W+\text{noise}\)\(B=0\), \(A\) small; check that step 0's outputs equal the base's exactly
merged logits differ slightly from the adapter model'sfloating-point association; about 1e-5 in fp32 is expectedcompare with a tolerance; merge in fp32 or fp64
LoRA matches full fine-tuning on one task, trails on anotherthe update needs more than rank \(r\), or too few modules are adaptedtune \(r\) and placement; keep a full fine-tuning baseline
memory barely drops after switching to LoRAactivations dominate; or parameters were frozen after AdamW had stepped, so their \(m\), \(v\) stay allocatedaudit requires_grad; rebuild the optimizer over the trainable parameters
a library LoRA run (e.g., Hugging Face peft) behaves strangelydefaults (which modules, how alpha is set) differ and drift across versionsreproduce one layer against your own class (Part 3)

Today's answer covers fine-tuning's cost and what LoRA buys and does not

Back to the title page's question, clause by clause.

  • What full fine-tuning costs: about 16 bytes per trained parameter before activations (104 GiB for 7B), and a full model per task.
  • How a low-rank update cuts it: freeze \(W\) and train \(\frac{\alpha}{r}BA\), \(r(d_{\text{in}}+d_{\text{out}})\) parameters; with \(B=0\), training starts at the pretrained model. 7B fits in about 13 GiB.
  • Why it costs nothing extra at inference: \(Wx+\frac{\alpha}{r}B(Ax)=\big(W+\frac{\alpha}{r}BA\big)x\); merged, the update is part of one matrix.
  • What adapting forgets: whatever the new task's loss never mentions. Replay brings most of it back; LoRA forgets as badly while attached, and removing it restores the base exactly.
  • How far the cheaper methods go: a 4-bit base fits 65B in about 32 GiB before activations; when the update must be high-rank, full fine-tuning learns more.

For next time

  • Next session (S20 + S21, one class), Wednesday: decoding (what each generation step costs, four samplers, prompting and in-context learning), then alignment (from demonstrations and preferences).
  • Read: 3.7, both halves: Decoding, Prompting, and In-Context Learning and Alignment: SFT, RLHF, DPO.
  • HW3 is due next Monday (S22); its generate task uses Wednesday's decoding material.
  • Project: the proposal is due at the end of next week (the S23 week).
  • Quiz 3 (Module 3) at S23, a week from Wednesday, covers today's material.