Full Fine-Tuning vs Parameter-Efficient Fine-Tuning
Full fine-tuning updates every weight. For a model with a few million parameters that is the simplest and usually the most accurate choice. For a 7-billion-parameter language model it means about 108 GB of GPU memory before a single activation is stored, and a new 13.5 GB copy of the model for every task. Parameter-efficient fine-tuning (PEFT) keeps the pretrained weights frozen and trains a small number of new or selected parameters, often well under 1 % of the model. This lesson counts what each choice costs, sorts the PEFT methods into families, and compares them on the same task.
Where the memory goes
Training with AdamW in mixed precision stores, for every trained parameter:
| What | Bytes per parameter |
|---|---|
| weight in 16-bit (bf16) for the forward and backward pass | 2 |
| gradient in 16-bit | 2 |
| float32 master copy of the weight | 4 |
| Adam first moment and second moment in float32 | 4 + 4 |
| total | 16 |
A frozen parameter needs only its 2-byte weight (or half a byte with 4-bit quantization). Activations, which grow with batch size and sequence length, come on top in both cases and are not counted here. The numbers for a Llama-2-7B-shaped model (32 layers, width 4096, feed-forward width 11,008, vocabulary 32,000), computed from its shape:
d, ffn, layers, vocab = 4096, 11008, 32, 32000
per_layer = 4 * d * d + 3 * d * ffn + 2 * d # q, k, v, o + gate, up, down + two norms
total = 2 * vocab * d + layers * per_layer + d # embeddings + output layer + blocks + final norm
r = 16 # LoRA rank on all seven linear layers of each block
lora = layers * r * (4 * (d + d) + 2 * (d + ffn) + (ffn + d))
GB = 1e9
print(f"parameters: {total / 1e9:.2f} billion | LoRA r = {r}: {lora / 1e6:.1f} million ({lora / total:.2%})")
print(f"full fine-tuning, 16 bytes each: {16 * total / GB:6.1f} GB")
print(f"LoRA: frozen bf16 weights + 16 B/LoRA: {(2 * total + 16 * lora) / GB:6.1f} GB")
print(f"QLoRA: 4-bit frozen weights + 16 B/LoRA:{(4.127 / 8 * total + 16 * lora) / GB:6.1f} GB")
print(f"storage per task: full copy {2 * total / GB:.1f} GB | LoRA adapter {2 * lora / 1e6:.0f} MB")parameters: 6.74 billion | LoRA r = 16: 40.0 million (0.59%)
full fine-tuning, 16 bytes each: 107.8 GB
LoRA: frozen bf16 weights + 16 B/LoRA: 14.1 GB
QLoRA: 4-bit frozen weights + 16 B/LoRA: 4.1 GB
storage per task: full copy 13.5 GB | LoRA adapter 80 MB
The shape gives 6.74 billion parameters. Training all of them needs 107.8 GB for weights, gradients and optimiser state: more than one 80 GB GPU. With LoRA of rank 16 on every linear layer, 40.0 million parameters train (0.59 %), and the total drops to 14.1 GB, almost all of it the frozen bf16 weights. Storing those frozen weights in 4 bits (QLoRA, 4.127 bits per weight including the quantization constants) brings it to 4.1 GB. Each task then adds an 80 MB adapter instead of a 13.5 GB copy. These are lower bounds: activations, and the temporary buffers of the framework, come on top and can be several GB at long sequence lengths.
The families of PEFT methods
- Selective methods train a subset of the existing parameters: the top layers (partial fine-tuning), only the bias vectors (BitFit, Ben Zaken et al., 2022), or only the layer-norm scales.
- Reparameterised methods write the update of a weight matrix in a cheaper form, with low-rank: LoRA (from scratch, with PEFT), DoRA (which adapts direction and length separately), and QLoRA, LoRA on a 4-bit base. The update merges into after training.
- Additive methods add new pieces: bottleneck adapters inside each block, IA3 vectors that rescale keys, values and feed-forward activations, or trainable input vectors: prompt tuning and prefix tuning (Adapters and Prompt Tuning).
From scratch: five ways to adapt the same network
The task of the LoRA lesson: the digit MLP pretrained on one half of the digits (64 hidden units), adapted to the other half shifted one pixel to the right, with 300 labelled images and 599 for testing, averaged over 3 draws. Every method trains a new 10-class head with Adam (rate 0.003, 300 full-batch steps), and adapts the first layer in its own way:
- head only: the first layer frozen (feature extraction);
- BitFit: the first layer's 64 biases train, its weights stay frozen;
- LoRA, : a rank-8 update of the 64 x 64 weight matrix;
- adapter, 8 units: a small bottleneck after the hidden layer, starting at zero;
- full: the whole first layer trains.
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier
X, y = load_digits(return_X_y=True)
X = X / 16.0
X_src, X_tgt, y_src, y_tgt = train_test_split(X, y, test_size=0.5, random_state=0, stratify=y)
source = MLPClassifier(hidden_layer_sizes=(64,), max_iter=500, random_state=0).fit(X_src, y_src)
W0, b0 = source.coefs_[0], source.intercepts_[0] # pretrained first layer, frozen unless trained
X_new = np.roll(X_tgt.reshape(-1, 8, 8), 1, axis=2).reshape(-1, 64) # target images: shifted 1 pixel right
def forward(P, A_in, s=1.0):
W = P["W"] if "W" in P else W0
if "A" in P:
W = W + s * P["A"] @ P["B"] # LoRA (row convention: h = x W)
pre = A_in @ W + P.get("b", b0)
h = np.maximum(0, pre)
a = np.maximum(0, h @ P["D"]) if "D" in P else None
h2 = h + a @ P["U"] if "D" in P else h # adapter with a residual connection
return pre, h, a, h2, h2 @ P["V"] + P["c"]
def train(P, Xl, yl, s=1.0, lr=0.003, steps=300):
m = {k: 0 for k in P}; v = {k: 0 for k in P}
for t in range(1, steps + 1):
pre, h, a, h2, z = forward(P, Xl, s)
p = np.exp(z - z.max(1, keepdims=True)); p /= p.sum(1, keepdims=True)
g = p.copy(); g[np.arange(len(yl)), yl] -= 1; g /= len(yl)
G = {"V": h2.T @ g, "c": g.sum(0)}
gh = g @ P["V"].T
if "D" in P:
G["U"] = a.T @ gh
ga = gh @ P["U"].T * (a > 0)
G["D"] = h.T @ ga
gh = gh + ga @ P["D"].T
gpre = gh * (pre > 0)
if "b" in P: G["b"] = gpre.sum(0)
if "W" in P: G["W"] = Xl.T @ gpre
if "A" in P:
GW = Xl.T @ gpre
G["A"], G["B"] = s * GW @ P["B"].T, s * P["A"].T @ GW
for k in P: # Adam
m[k] = 0.9 * m[k] + 0.1 * G[k]; v[k] = 0.999 * v[k] + 0.001 * G[k] ** 2
P[k] = P[k] - lr * (m[k] / (1 - 0.9 ** t)) / (np.sqrt(v[k] / (1 - 0.999 ** t)) + 1e-8)
return P
def new_params(method, rng):
P = {"V": rng.normal(0, 0.1, (64, 10)), "c": np.zeros(10)} # every method: a new head
if method == "BitFit":
P["b"] = b0.copy()
if method == "LoRA r=8":
P["A"], P["B"] = rng.normal(0, 1 / np.sqrt(64), (64, 8)), np.zeros((8, 64))
if method == "adapter 8":
P["D"], P["U"] = rng.normal(0, 1 / np.sqrt(64), (64, 8)), np.zeros((8, 64))
if method == "full":
P["W"], P["b"] = W0.copy(), b0.copy()
return P
print("method trainable share of the network test accuracy (599 images, 3 draws)")
network = W0.size + b0.size + 650
for method in ["head only", "BitFit", "LoRA r=8", "adapter 8", "full"]:
accs = []
for seed in range(3):
rng = np.random.default_rng(seed)
lab = np.concatenate([rng.choice(np.where(y_tgt == c)[0], 30, replace=False) for c in range(10)])
test = np.setdiff1d(np.arange(len(y_tgt)), lab)
P = train(new_params(method, rng), X_new[lab], y_tgt[lab], s=1.0)
accs.append((forward(P, X_new[test])[4].argmax(1) == y_tgt[test]).mean())
n = sum(p.size for p in new_params(method, rng).values())
print(f"{method:12s} {n:9d} {n / network:20.1%} {np.mean(accs):.3f}")method trainable share of the network test accuracy (599 images, 3 draws)
head only 650 13.5% 0.899
BitFit 714 14.8% 0.900
LoRA r=8 1674 34.8% 0.935
adapter 8 1674 34.8% 0.912
full 4810 100.0% 0.942
On this small network the methods line up by how much of the first layer they can change. BitFit, 64 extra numbers, adds nothing over the frozen layer (0.900 against 0.899): shifting each unit's threshold cannot undo a shifted input. The adapter (0.912) helps a little; it works after the hidden layer and can only recombine features the frozen layer already computed. LoRA changes the first layer's weights themselves and gets to 0.935, within 0.007 (four images) of full fine-tuning at 0.942.
The shares look large (35 % for LoRA) because the network is tiny and the head alone is 13.5 % of it. The trainable counts scale very differently with size: for a 4096-wide layer, LoRA is 0.4 % of the matrix and an 8-unit adapter about the same, while the head stays a few thousand numbers. A single learning rate (0.003) and 300 steps were used for every method, which favours none in particular but is not a tuned comparison.
The same families in Hugging Face PEFT
PEFT implements all three families behind one call, get_peft_model(model, config). Wrapping the small pretrained BERT of this course (google/bert_uncased_L-2_H-128_A-2, 4.4 million parameters) with four configs and counting what would train:
import torch
from transformers import AutoModelForSequenceClassification
from transformers.utils import logging
from peft import LoraConfig, IA3Config, PromptTuningConfig, PrefixTuningConfig, get_peft_model
logging.set_verbosity_error() # hide the "classifier newly initialised" load report
name = "google/bert_uncased_L-2_H-128_A-2"
ffn_out = r".*layer\.\d+\.output\.dense" # the second feed-forward layer of each block (not attention.output)
configs = {
"LoRA r=8 (query, value)": LoraConfig(task_type="SEQ_CLS", r=8, lora_alpha=16, target_modules=["query", "value"]),
"IA3 (key, value, ffn)": IA3Config(task_type="SEQ_CLS", target_modules=rf"(.*\.(key|value))|({ffn_out})",
feedforward_modules=ffn_out),
"prompt tuning, 20 tokens": PromptTuningConfig(task_type="SEQ_CLS", num_virtual_tokens=20),
"prefix tuning, 20 tokens": PrefixTuningConfig(task_type="SEQ_CLS", num_virtual_tokens=20),
}
x = torch.tensor([[101, 2023, 3185, 2001, 2307, 102]]) # "[CLS] this movie was great [SEP]"
for label, config in configs.items():
torch.manual_seed(0)
model = get_peft_model(AutoModelForSequenceClassification.from_pretrained(name, num_labels=2), config)
trainable, total = model.get_nb_trainable_parameters()
logits = model(input_ids=x, attention_mask=torch.ones_like(x)).logits
print(f"{label:25s} trainable {trainable:>6,} of {total:,} ({trainable / total:.2%}) logits {tuple(logits.shape)}")LoRA r=8 (query, value) trainable 8,450 of 4,394,628 (0.19%) logits (1, 2)
IA3 (key, value, ffn) trainable 1,794 of 4,387,972 (0.04%) logits (1, 2)
prompt tuning, 20 tokens trainable 2,818 of 4,388,996 (0.06%) logits (1, 2)
prefix tuning, 20 tokens trainable 10,498 of 4,396,676 (0.24%) logits (1, 2)
Four methods, four orders of magnitude below the model's size. LoRA on query and value trains 8,450 numbers (0.19 %). IA3 trains only one scaling vector per adapted layer: 128 each for keys and values and 512 for the feed-forward activation in each of the 2 blocks, plus the head, 1,794 in all (0.04 %). Prompt tuning learns 20 input vectors of width 128 (2,560 plus the head, 0.06 %), and prefix tuning 20 key and 20 value vectors in each of the 2 layers (10,240 plus the head, 0.24 %). Every wrapped model still produces one pair of logits per sentence; the adapters and prompt tuning lesson trains them.
Full or parameter-efficient?
| Full fine-tuning | PEFT (LoRA, adapters, prompts) | |
|---|---|---|
| Trainable parameters | all | typically 0.01 % to 1 % |
| Training memory | 16 bytes per parameter + activations | ~2 bytes (or 0.5 with 4 bits) per frozen parameter + activations |
| Storage per task | a full model copy | a few MB |
| Serving many tasks | one model per task | one base, adapters switched per request |
| Accuracy | the reference; best when the task is far from pretraining and labels are plentiful | close to full on most tasks, sometimes better with little data; can lag on very different domains |
| Forgetting | the most | less (the base is intact), not zero |
| Speed per step | slower (all gradients) | faster, but the frozen base still runs forward and backward |
Rules of thumb. Small models (up to a few hundred million parameters) on a capable GPU: full fine-tuning is fine and often slightly better. Large models, one GPU, many tasks or customers: LoRA, QLoRA if memory is still short. Very many tasks with tiny per-task storage, and a very large model: prompt tuning. When in doubt, LoRA on all linear layers is the robust default.
Pitfalls
- Counting only trainable parameters. PEFT reduces optimiser and gradient memory, not the activations or the frozen weights. A long sequence length can still run out of memory.
- Calling the new head "parameter-efficient". For a new classification task the head trains in full in every method; it is small, but forgetting to train it is a classic bug.
- Comparing methods at different learning rates by accident. Each method has its own good range (LoRA and prompts want larger rates than full fine-tuning); sweep each one or say that a single rate was used, as above.
- Assuming PEFT is always worse. With few labels the restriction regularises and can beat full fine-tuning, as the LoRA experiment with a rank-2 change shows.
Practice
- A 1.3-billion-parameter model is fine-tuned in full with AdamW in mixed precision. Roughly how much GPU memory do the weights, gradients and optimiser state need?
- In the PEFT table, why does prefix tuning have more trainable parameters than prompt tuning with the same 20 virtual tokens?
- A team serves 200 customers, each with a fine-tuned variant of one 7B model. Compare the storage for full fine-tuning and for LoRA adapters of 80 MB.
Answers
- bytes GB, plus activations.
- Prompt tuning learns 20 vectors at the input only (). Prefix tuning learns 20 key and 20 value vectors in every layer: for 2 layers.
- Full: GB TB. LoRA: one 13.5 GB base plus MB GB, about 30 GB in total.
Test yourself
Why does full fine-tuning with AdamW in mixed precision need about 16 bytes per parameter?
- Because weights are stored in float64
- 16-bit weight and gradient, a float32 master copy, and two float32 Adam moments: 2 + 2 + 4 + 4 + 4
- Because activations take 16 bytes
- Because of the tokenizer
Which method is reparameterised rather than additive or selective?
- BitFit
- Prompt tuning
- LoRA
- Training the top two layers
What does PEFT not reduce?
- Optimiser state memory
- Gradient memory
- Activation memory for long sequences
- Storage per task