Session S19
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
Before the material, where HW3, the project and Quiz 3 stand.
generate task (greedy decoding at temperature 0, sampling otherwise) uses Wednesday's material (S20).Today adapts a model like the one S18 pretrained. From S18:
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.
Five parts, each answering one clause of the title page's question; a sixth closes.
| part | the question it answers |
|---|---|
| 1 · The memory cost | what 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 update | how 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 scratch | why does the trained update cost nothing extra at inference? The class from scratch, a training run, and the check that merging changes nothing |
| 4 · Forgetting | what 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 limits | how far can the cheaper methods go? LoRA's relatives, a base stored in 4 bits (QLoRA), and when full fine-tuning still wins |
| 6 · Close | common mistakes, today's answer, next time |
Each of Parts 1–5 ends on a self-check. First, the memory cost.
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:
The training state is about four times the fp32 weights, before a single activation.
Mixed precision saves time and activation memory, not training state: both layouts cost 16 bytes.
Two ways to fine-tune a model with \(N\) parameters. The second, LoRA, previews Part 2: freeze the pretrained weights, train about 0.1%.
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.
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):
| model | parameters | full fine-tuning, GiB | needs | LoRA, frozen base, GiB | needs |
|---|---|---|---|---|---|
| GPT-2 small (S18) | 124M | 1.8 | one 24 GB card | 0.2 | one 24 GB card |
| 7B, the prediction | 7.0B | 104.3 | two 80 GB cards | 13.1 | one 24 GB card |
| Mistral 7B | 7.2B | 107.3 | two 80 GB cards | 13.5 | one 24 GB card |
| Llama 3.1 8B | 8.0B | 119.2 | two 80 GB cards | 15.0 | one 24 GB card |
| Llama 3.1 70B | 70.6B | 1052.0 | fourteen 80 GB cards | 132.6 | two 80 GB cards |
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 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.
(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:
What today cuts is the training state and the full model per task: LoRA saves both, and Part 3 returns to the second.
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.
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\]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}\]Only the correction is constrained to be simple; the pretrained \(W\) stays as rich as it was.
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}\]\(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\):
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.
The first of three design details (reading 3.6).
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\).
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\):
Each gradient carries the other factor: \(dB\) through \(H=XA^{\top}\), \(dA\) through \(dH=s\,dY\,B\).
| 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 |
With \(B=0\) training starts at the pretrained model and still moves; with both zero it never leaves it.
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 · LoRA from scratch. First the whole model, reading 3.6's small network, then the code that builds it.
Orange is trained and hatched is frozen. The next pages write the class (p21), wrap one layer (p22), then build this model (p23).
nn.Linear and adds the low-rank pathReading 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).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
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.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%?
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 + bias | LoRA, \(r(d_{\text{in}}+d_{\text{out}})\) | LoRA / \(W\)'s entries |
|---|---|---|---|---|
model[0] | 64 → 128 | 8,320 | 768 | 768 / 8,192 = 9.4% |
model[2] | 128 → 10 | 1,290 | 552 | 552 / 1,280 = 43.1% |
| both | 9,610 | 1,320 | 1,320 / 10,930 = 12.08% of all |
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
nn.Linear and comparesAfter 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
torch.allclose with a sensible atol), not torch.equal.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:
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.
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:
To do well on B, the model must change how it maps each symbol to the next.
The three methods train different parts of the same model.
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
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.
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
One frozen base plus one small adapter per task serves every task without interference.
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.
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.
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.
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)]
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
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 when | choose 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 tokens | you 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 hardware | keeping general ability or swapping tasks cheaply is the point; or you have a few hundred examples, where full fine-tuning mostly buys overfitting |
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.
Part 6 · Close. Reading 3.6's pitfalls, and its caution about libraries:
| symptom | cause | fix |
|---|---|---|
| out of memory, though the checkpoint fits the GPU easily | 16 bytes per trained parameter, plus activations | do 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's | floating-point association; about 1e-5 in fp32 is expected | compare with a tolerance; merge in fp32 or fp64 |
| LoRA matches full fine-tuning on one task, trails on another | the update needs more than rank \(r\), or too few modules are adapted | tune \(r\) and placement; keep a full fine-tuning baseline |
| memory barely drops after switching to LoRA | activations dominate; or parameters were frozen after AdamW had stepped, so their \(m\), \(v\) stay allocated | audit requires_grad; rebuild the optimizer over the trainable parameters |
a library LoRA run (e.g., Hugging Face peft) behaves strangely | defaults (which modules, how alpha is set) differ and drift across versions | reproduce one layer against your own class (Part 3) |
Back to the title page's question, clause by clause.
generate task uses Wednesday's decoding material.