Adapters and Prompt Tuning
LoRA adapts a frozen model by changing what its weight matrices compute. Two older families of parameter-efficient methods leave every weight matrix exactly as it is and add something instead. Adapters insert small trainable layers inside each block of the network. Prompt tuning and prefix tuning do not touch the network at all: they learn a few extra input vectors, "virtual tokens" that the frozen model reads along with the real input. This lesson builds an adapter in NumPy, shows how a soft prompt enters attention, and trains both kinds on a pretrained BERT.
Adapters
A bottleneck adapter (Houlsby et al., 2019) is a tiny two-layer network with a residual connection, inserted after a sublayer of a transformer block:
- It has parameters per insertion; with and that is 99,136, against 7 million in a BERT-base block.
- starts at zero (or near zero), so the adapter is the identity at the start and the network computes exactly what the pretrained one did, the same trick as LoRA's .
- Where: Houlsby adapters sit after the attention sublayer and after the feed-forward sublayer of every block; the Pfeiffer variant uses only the one after the feed-forward sublayer, at half the cost and usually similar accuracy. Layer norms and the new head train as well.
- Inference cost: because of the nonlinearity , an adapter cannot be merged into the neighbouring weights. Every adapter is an extra sequential layer at inference, a few percent of latency. That is the main practical reason LoRA has overtaken adapters for LLMs.
From scratch: an adapter, and where to put it
The digit network of the LoRA lesson (64 hidden units, pretrained on one half of the digits, adapted to the other half shifted by one pixel, 300 labelled images, 599 test images, 3 draws). Its weights stay frozen; only adapters and a new head train, with Adam at 0.003 for 300 steps. The question is placement: an adapter after the hidden layer (where a transformer would put it) or one on the input, before the frozen first layer, where the shift happened.
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] # frozen pretrained layer
X_new = np.roll(X_tgt.reshape(-1, 8, 8), 1, axis=2).reshape(-1, 64) # target: shifted 1 pixel right
def adapter(Z, D, U): # Z + ReLU(Z D) U, U starts at 0
a = np.maximum(0, Z @ D)
return a, Z + a @ U
def adapter_backward(Z, a, D, U, g_out): # gradients for D, U and the adapter input
gU = a.T @ g_out
ga = g_out @ U.T * (a > 0)
return Z.T @ ga, gU, g_out + ga @ D.T
def train(places, m, rng, Xl, yl, lr=0.003, steps=300):
P = {"V": rng.normal(0, 0.1, (64, 10)), "c": np.zeros(10)} # new head
for w in places:
P["D" + w], P["U" + w] = rng.normal(0, 1 / np.sqrt(64), (64, m)), np.zeros((m, 64))
def forward(A):
a_in, x = adapter(A, P["Din"], P["Uin"]) if "Din" in P else (None, A)
pre = x @ W0 + b0
h = np.maximum(0, pre)
a_h, h2 = adapter(h, P["Dhid"], P["Uhid"]) if "Dhid" in P else (None, h)
return a_in, pre, h, a_h, h2, h2 @ P["V"] + P["c"]
mom = {k: 0 for k in P}; vel = {k: 0 for k in P}
for t in range(1, steps + 1):
a_in, pre, h, a_h, h2, z = forward(Xl)
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 "Dhid" in P:
G["Dhid"], G["Uhid"], gh = adapter_backward(h, a_h, P["Dhid"], P["Uhid"], gh)
if "Din" in P: # back through the frozen layer to the input adapter
G["Din"], G["Uin"], _ = adapter_backward(Xl, a_in, P["Din"], P["Uin"], (gh * (pre > 0)) @ W0.T)
for k in P: # Adam
mom[k] = 0.9 * mom[k] + 0.1 * G[k]; vel[k] = 0.999 * vel[k] + 0.001 * G[k] ** 2
P[k] = P[k] - lr * (mom[k] / (1 - 0.9 ** t)) / (np.sqrt(vel[k] / (1 - 0.999 ** t)) + 1e-8)
return lambda A: forward(A)[-1].argmax(1), sum(p.size for p in P.values())
print("adapters trainable test accuracy (599 images, 3 draws)")
for label, places, m in [("none (head only)", (), 0), ("after hidden, m = 8", ("hid",), 8),
("on the input, m = 8", ("in",), 8), ("on the input, m = 32", ("in",), 32),
("both, m = 8", ("in", "hid"), 8)]:
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)
predict, n = train(places, m, rng, X_new[lab], y_tgt[lab])
accs.append((predict(X_new[test]) == y_tgt[test]).mean())
print(f"{label:24s} {n:10d} {np.mean(accs):.3f}")adapters trainable test accuracy (599 images, 3 draws)
none (head only) 650 0.899
after hidden, m = 8 1674 0.912
on the input, m = 8 1674 0.924
on the input, m = 32 4746 0.933
both, m = 8 2698 0.910
Placement matters more than size. After the hidden layer, an 8-unit adapter adds a little to the head alone (0.912 against 0.899). On the input it does clearly better (0.924) with the same 1,674 trainable numbers, and with 32 units 0.933, close to LoRA's 0.935 in the LoRA lesson and full fine-tuning's 0.940 there. The shift happened at the input, so a correction at the input is where it can be undone; after the frozen layer the information about the misplaced pixels is already mixed. Two adapters of 8 units (0.910) do not beat the input one alone in this budget of 300 steps; with scores averaged over only 3 draws of 599 test images, differences of 0.01 (six images) are at the edge of what this test can resolve. Transformers put adapters in every block for the same reason: wherever the task needs a change, one is nearby.
Prompt tuning and prefix tuning
A transformer reads a sequence of embedding vectors. Prompt tuning (Lester et al., 2021) prepends trainable vectors to the embeddings of every input, and trains only (and a new head, for classification):
These soft prompts are not words: they are free vectors that gradient descent shapes so that the frozen model, reading them, behaves as the task needs. 20 tokens on a model of width 4096 are 81,920 numbers, about 0.001 % of a 7B model. The catch is expressiveness: the prompt can only influence the network through attention to those positions. Prompt tuning matches full fine-tuning only for very large models (around 10 billion parameters in Lester et al.'s experiments) and lags far behind on small ones.
Prefix tuning (Li and Liang, 2021) gives every layer its own prefix: trainable key and value vectors that are prepended to that layer's keys and values, , . That is parameters and much more direct control over every layer's attention. P-tuning v2 is the same idea applied to classification and smaller models.
Unlike LoRA and zero-initialised adapters, neither method starts at the pretrained function: every real token attends to the new vectors from the first step. A few lines of NumPy show the mechanics on one frozen attention head:
import numpy as np
rng = np.random.default_rng(0)
d, T, p = 8, 5, 3 # width, real tokens, soft-prompt tokens
E = rng.normal(size=(T, d)) # embeddings of the real input (frozen lookup)
Wq, Wk, Wv = (rng.normal(size=(d, d)) / np.sqrt(d) for _ in range(3)) # frozen attention weights
def attention(H, mask):
Q, K, V = H @ Wq, H @ Wk, H @ Wv
s = Q @ K.T / np.sqrt(d) + np.where(mask[None, :], 0.0, -1e9) # padding/invalid keys get -inf
w = np.exp(s - s.max(1, keepdims=True)); w /= w.sum(1, keepdims=True)
return w, w @ V
w0, out0 = attention(E, np.ones(T, bool))
P = rng.normal(0, 0.5, (p, d)) # the soft prompt: the only trainable numbers
H = np.vstack([P, E]) # prepend: (p + T) x d
mask = np.ones(p + T, bool) # the attention mask grows by p ones
w1, out1 = attention(H, mask)
print("input shape", E.shape, "-> with prompt", H.shape)
print("token 1 attention to the 3 prompt positions:", w1[p, :p].round(3), "| total", round(float(w1[p, :p].sum()), 3))
print("token 1 output changed by the prompt:", round(float(np.linalg.norm(out1[p] - out0[0])), 3))
for name, width, layers in [("BERT-base", 768, 12), ("7B LLM", 4096, 32)]:
print(f"{name:9s} 20 virtual tokens: prompt tuning {20 * width:,} numbers, prefix tuning {2 * layers * 20 * width:,}")input shape (5, 8) -> with prompt (8, 8)
token 1 attention to the 3 prompt positions: [0.097 0.186 0.162] | total 0.446
token 1 output changed by the prompt: 0.637
BERT-base 20 virtual tokens: prompt tuning 15,360 numbers, prefix tuning 368,640
7B LLM 20 virtual tokens: prompt tuning 81,920 numbers, prefix tuning 5,242,880
With 3 prompt vectors prepended, the sequence grows from 5 to 8 positions and the attention mask by 3 ones. The first real token now spends 0.446 of its attention on the prompt positions, and its output vector moves by 0.637: before any training, the model already computes something different from the pretrained one. Training the prompt chooses what that difference is. The counts at the end show the scale: prompt tuning with 20 tokens is 15,360 numbers for BERT-base and 81,920 for a 7B model; prefix tuning, with keys and values in every layer, is 24 and 64 times more, still tiny next to the models.
With PEFT: soft prompts on a pretrained BERT
The same small BERT (google/bert_uncased_L-2_H-128_A-2) and data (2,000 training and 500 test sentences of rotten_tomatoes, 48 word pieces, 3 epochs, batches of 32) as the LoRA with PEFT and partial fine-tuning lessons, so the scores compare directly. Soft prompts want large learning rates; both runs use (a short check found too large for prefix tuning and too small).
import torch
from datasets import load_dataset
from transformers import AutoTokenizer, AutoModelForSequenceClassification
from transformers.utils import logging
from peft import 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"
ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
train = ds["train"].shuffle(seed=0).select(range(2000))
test = ds["test"].shuffle(seed=0).select(range(500))
tok = AutoTokenizer.from_pretrained(name)
enc = lambda d: tok(list(d["text"]), padding="max_length", truncation=True, max_length=48, return_tensors="pt")
X_tr, X_te = enc(train), enc(test)
y_tr, y_te = torch.tensor(train["label"]), torch.tensor(test["label"])
def fit_and_score(model, lr, epochs=3):
opt = torch.optim.AdamW([p for p in model.parameters() if p.requires_grad], lr=lr)
g = torch.Generator().manual_seed(0)
for _ in range(epochs):
model.train()
for idx in torch.randperm(len(y_tr), generator=g).split(32):
out = model(input_ids=X_tr["input_ids"][idx], attention_mask=X_tr["attention_mask"][idx], labels=y_tr[idx])
opt.zero_grad(); out.loss.backward(); opt.step()
model.eval()
with torch.no_grad():
logits = model(input_ids=X_te["input_ids"], attention_mask=X_te["attention_mask"]).logits
return (logits.argmax(1) == y_te).float().mean().item()
for label, config in [("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))]:
torch.manual_seed(0)
model = get_peft_model(AutoModelForSequenceClassification.from_pretrained(name, num_labels=2), config)
trainable, _ = model.get_nb_trainable_parameters()
print(f"{label:25s} trainable {trainable:>6,} test accuracy {fit_and_score(model, 3e-2):.3f}")prompt tuning, 20 tokens trainable 2,818 test accuracy 0.652
prefix tuning, 20 tokens trainable 10,498 test accuracy 0.654
| Method on the same BERT and data | Trainable | Test accuracy (500 sentences) |
|---|---|---|
| head only (partial fine-tuning) | 258 | 0.574 |
| prompt tuning, 20 tokens | 2,818 | 0.652 |
| prefix tuning, 20 tokens | 10,498 | 0.654 |
| LoRA r = 8 on query + value (LoRA with PEFT) | 8,450 | 0.704 |
| full fine-tuning | 4,386,178 | 0.742 |
Both soft-prompt methods beat a head on the frozen encoder (0.652 and 0.654 against 0.574) and both stay well below LoRA with a similar number of parameters (0.704). On a 4.4-million-parameter model that is the expected result: prompts act only through attention, and a small model has little "programmable" behaviour for them to steer. The standard error on 500 sentences is about 0.02, so prompt and prefix tuning are tied here, while the gap to LoRA (0.05) and to full fine-tuning (0.09) is real.
Comparing the additive methods
| Method | Trainable per layer | Starts at the pretrained model | Extra inference cost | Strong when |
|---|---|---|---|---|
| Bottleneck adapter | per insertion | yes () | an extra small layer per insertion | moderate model sizes, many tasks, composable adapters (AdapterFusion) |
| IA3 | scaling vectors | yes (vectors start at 1) | none after merging the scales | very few parameters, few-shot tasks |
| Prompt tuning | in total (input only) | no | extra tokens per sequence | very large models, many tasks batched together |
| Prefix tuning | no | extra keys and values per layer | generation tasks, mid-size models | |
| LoRA (for reference) | per matrix | yes () | none after merging | the general default |
A practical property of prompt tuning: since the model is untouched, one batch can mix inputs from many tasks, each with its own prompt, served by a single copy of the model.
Pitfalls
- Adapter up-projection initialised at random. The network then starts from a perturbed model; initialise at zero or very small.
- Small learning rates for prompts. Soft prompts often need or more (Lester et al. used 0.3 with Adafactor); with a full fine-tuning rate they barely move.
- Expecting prompt tuning to work on a small model. Its accuracy grows with model size; on models of a few hundred million parameters or less, prefer LoRA or adapters.
- Prompt length eating the context. 100 virtual tokens are 100 fewer positions for real text, and attention cost grows with them.
- Initialising prompts at random for small models. Initialising the prompt from the embeddings of real words describing the task (PEFT's
prompt_tuning_init="TEXT") often trains faster and more stably.
Practice
- An adapter with is inserted twice in each of the 12 blocks of a model with . How many adapter parameters is that?
- Why can a LoRA update be merged into the weights after training, but a bottleneck adapter cannot?
- In the NumPy experiment, why does the input adapter do better than the one after the hidden layer?
Answers
- Per insertion ; insertions give 608,640.
- LoRA's update is linear, , so it folds into one matrix. An adapter has a nonlinearity between its two projections, so its effect cannot be written as a change of a neighbouring weight matrix.
- The shift changed the input, and the frozen first layer looks at the wrong pixels. An adapter on the input can learn a correction of the pixels before the frozen layer sees them; an adapter after the hidden layer can only recombine features that were already computed from the wrong pixels.
Test yourself
What does prompt tuning train?
- All attention weights
- A few continuous vectors prepended to the input embeddings (plus a head for classification)
- The tokenizer vocabulary
- The layer norms only
Why is the up-projection of a bottleneck adapter initialised to zero?
- To make the adapter faster
- So that the adapter is the identity and the network starts exactly as the pretrained one
- To reduce its rank
- Because ReLU needs it
How does prefix tuning differ from prompt tuning?
- It trains the whole model
- It prepends trainable key and value vectors in every layer instead of input vectors only
- It uses no virtual tokens
- It merges into the weights