Prefix Tuning › The Prefix Tuning Formulation

Michael BrenndoerferDecember 7, 202518 min read
Language AI HandbookAll chapters
Part 35 of 67Parameter-Efficient Fine-tuning
Chapter 262Prefix Tuning › The Prefix Tuning Formulation
Reading section 2 of 11 · The Prefix Tuning Formulation · 18 minSection 2 of 11 · 18 min

Book contents

Section 2 of 11 · 18 min read

Prefix Tuning › The Prefix Tuning FormulationOne section · Sections in this chapter2 / 11 ↓
Reading tools Definitions & inline links

Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.

Article links

Make inline references clickable

To understand prefix tuning deeply, we must first revisit how attention works and why modifying its inputs can be so effective. The attention mechanism determines which parts of the input sequence should influence each other. Through attention, the model learns to associate words with their contexts, track references across long distances, and reason about relationships between ideas. Modifying what attention sees can therefore have a large effect. A small change to the inputs can propagate through the softmax normalization to produce large changes in the output distribution.

As discussed in previous chapters, scaled dot-product attention computes a weighted combination of value vectors, where the weights are determined by the compatibility between query and key vectors. The computation requires three matrices derived from the input: queries that stand for what each position is looking for, keys that stand for what each position offers, and values that stand for the actual information to be retrieved. The beauty of this design is that all three can be separately controlled, which is precisely what prefix tuning exploits.

The standard scaled dot-product attention formula is:

Attention(Q,K,V)=softmax(QKTdk)V\text{Attention}(Q, K, V) = \text{softmax}\left(\frac{QK^T}{\sqrt{d_k}}\right)V

where:

  • QQ: the query matrix, containing row vectors representing "what we are looking for" at each sequence position
  • KK: the key matrix, containing row vectors representing "what each position offers" for matching
  • VV: the value matrix, containing row vectors with "what we retrieve" when a match is found
  • dkd_k: the dimension of the key vectors, used as a scaling factor
  • softmax\text{softmax}: the function converting raw attention scores into a probability distribution over positions

We scale by dk\sqrt{d_k} to prevent the dot products from growing too large in high dimensions, which would cause vanishing gradients in the softmax. To see why this matters: in a dkd_k-dimensional space, if QQ and KK contain random unit vectors, the expected magnitude of their dot product is dk\sqrt{d_k}. Without the scaling factor, attention scores for a model with dk=1024d_k = 1024 would be roughly 32 times larger than for one with dk=1d_k = 1, causing the softmax to become nearly one-hot (peaking sharply at the highest score) and preventing smooth gradient flow. Dividing by dk\sqrt{d_k} keeps attention scores in a well-behaved range regardless of model dimensionality.

These matrices are derived from input representations through learned linear projections. In standard transformers, these matrices come from projecting the input sequence X∈Rn×dX \in \mathbb{R}^{n \times d}:

Q=XWQ,K=XWK,V=XWVQ = XW_Q, \quad K = XW_K, \quad V = XW_V

where:

  • XX: the input sequence matrix of shape n×dn \times d, with one row per token and dd columns per model dimension
  • WQW_Q: the learnable query projection matrix, mapping from dd-dimensional input to dkd_k-dimensional query space
  • WKW_K: the learnable key projection matrix, mapping from dd-dimensional input to dkd_k-dimensional key space
  • WVW_V: the learnable value projection matrix, mapping from dd-dimensional input to dvd_v-dimensional value space

This formulation reveals two potential ways to adapt model behavior. We could modify the projection matrices WQW_Q, WKW_K, and WVW_V, which is the approach taken by methods like LoRA. Alternatively, we could modify what these projections operate on by changing the sequences that become keys and values. Prefix tuning chooses the latter path, leaving all projection matrices completely frozen.

The key insight is that extending the key and value sequences with additional learnable vectors gives every attention head, at every layer, access to new information sources. When a query at any position computes attention scores, it now scores the nn real input positions and the mm virtual prefix positions. The softmax normalization then redistributes attention weights over this extended set. This redistribution is how the prefix "steers" the model: by giving high-quality key-value pairs that receive attention, the prefix can shape which information gets retrieved and aggregated at every position.

Prefix tuning modifies the attention computation by prepending learnable prefix vectors to both keys and values. Let PK∈Rm×dkP_K \in \mathbb{R}^{m \times d_k} and PV∈Rm×dvP_V \in \mathbb{R}^{m \times d_v} be learnable prefix matrices, where mm is the prefix length. The modified attention becomes:

K′=[PK;K],V′=[PV;V]K' = [P_K; K], \quad V' = [P_V; V]

where:

  • K′K': the extended key matrix of shape (m+n)×dk(m + n) \times d_k
  • V′V': the extended value matrix of shape (m+n)×dv(m + n) \times d_v
  • PKP_K: learnable prefix matrix of shape m×dkm \times d_k, containing the virtual key vectors
  • PVP_V: learnable prefix matrix of shape m×dvm \times d_v, containing the virtual value vectors
  • KK: original key matrix of shape n×dkn \times d_k, derived from the real input
  • VV: original value matrix of shape n×dvn \times d_v, derived from the real input
  • [;][;]: concatenation operation along the sequence dimension (vertical stacking)

The semicolon notation indicates vertical stacking of matrices: we place the prefix matrices above the original matrices, effectively creating longer sequences. This means that when we compute attention, every query position can now attend to the original nn key positions and to these mm new prefix positions. The prefix positions give additional "options" for the attention mechanism to draw information from.

The full modified attention computation then attends over the extended sequences:

Attention(Q,K′,V′)=softmax(QK′Tdk)V′\text{Attention}(Q, K', V') = \text{softmax}\left(\frac{Q{K'}^T}{\sqrt{d_k}}\right)V'

where:

  • QQ: the query matrix of shape n×dkn \times d_k (unchanged, derived only from real input tokens)
  • K′K': the extended key matrix of shape (m+n)×dk(m + n) \times d_k
  • V′V': the extended value matrix of shape (m+n)×dv(m + n) \times d_v
  • dkd_k: the key dimension, used as the scaling factor
  • softmax\text{softmax}: now normalizes over m+nm + n positions rather than the original nn

Notice that the queries remain unchanged: we do not prepend anything to them. This asymmetry is intentional and important. The queries stand for what each position in our sequence is looking for. By keeping queries tied to the actual input positions, we ensure that the output sequence maintains the same length as the input. The output of attention remains an n×dvn \times d_v matrix, one row per real input token. The prefixes influence computation by giving additional things to attend to, not additional positions that produce outputs.

Out[4]:
Visualization
Heatmap of an attention matrix where 8 query positions (rows T1-T8) attend over 13 key positions (columns P1-P5 for prefix tokens and T1-T8 for input tokens), separated by a red dashed line, with labeled annotation boxes for prefix and input key regions.
Attention matrix structure showing input tokens attending to both prefix virtual tokens and actual input positions. Rows stand for queries while columns stand for keys, with the leftmost block showing task-specific steering from virtual tokens. Darker shades reveal higher weights, showing how input tokens draw information from both sources.
Virtual Tokens

The prefix vectors PKP_K and PVP_V are called "virtual tokens" because they occupy positions in the sequence that no real input token corresponds to. Unlike token embeddings constrained to the model's vocabulary, these vectors live in continuous space and can stand for arbitrary concepts. This freedom from the discrete vocabulary is what gives prefix tuning its expressive power: the learned vectors can encode task-specific information that no combination of real tokens could express as efficiently. A virtual token can simultaneously blend the semantic content of multiple words, encode abstract stylistic preferences, and carry syntactic cues, all without being constrained to match any particular entry in the embedding table.

Layer-Specific Prefixes

A necessary detail distinguishes prefix tuning from simpler approaches: prefix tuning introduces separate prefix vectors at each transformer layer, not just at the input. This distinguishes it from methods that only modify the input embedding layer. For a model with LL layers, prefix tuning learns a complete set of layer-specific prefix matrices:

{PK(1),PV(1),PK(2),PV(2),…,PK(L),PV(L)}\{P_K^{(1)}, P_V^{(1)}, P_K^{(2)}, P_V^{(2)}, \ldots, P_K^{(L)}, P_V^{(L)}\}

where:

  • PK(l),PV(l)P_K^{(l)}, P_V^{(l)}: learnable prefix matrices for the ll-th transformer layer, each of shape m×dkm \times d_k and m×dvm \times d_v respectively
  • LL: the total number of transformer layers in the frozen pretrained model

This layer-specific design is needed for achieving strong performance, and understanding why requires appreciating how transformers process information hierarchically. Each layer of a transformer captures different levels of abstraction. Early layers (roughly the first quarter) often detect basic linguistic features like word boundaries, morphological patterns, and simple grammatical structures. Middle layers build up more complex representations involving phrases and clauses, including syntactic dependencies. Later layers capture high-level semantic relationships, discourse coherence, and task-needed features such as sentiment or logical structure. By learning prefixes at each layer, prefix tuning can guide representations at every level of the hierarchy. This gives layer-appropriate steering signals that accumulate into coherent task-specific behavior.

Think of the layer-specific design as having a different co-pilot at each altitude of flight. At low altitude, the co-pilot gives instructions about staying in the lane and avoiding obstacles (syntactic details). At cruising altitude, they give navigational guidance about heading and speed (semantic structure). At high altitude, they advise on flight plan and destination (task-level objectives). Each set of instructions is specialized for the altitude at which it operates, and their combined effect is a smooth, coherent journey to the right destination.

If we only added prefixes at the input layer, the steering signal would need to propagate through all subsequent layers without refreshing. Research on information propagation in transformers has shown that signals injected at the input layer tend to attenuate as they pass through successive attention and feed-forward operations. By injecting fresh task guidance at every layer, prefix tuning ensures that the model receives consistent direction throughout its entire processing pipeline. The prefix at layer ll does not need to survive unchanged through L−lL - l layers of transformation; instead, it gives appropriate guidance at exactly the point in processing where that guidance is needed.

Out[5]:
Visualization
Architectural diagram showing 6 stacked frozen transformer layers (gray boxes) each receiving trainable prefix matrices P_K and P_V (teal boxes) via arrows from the left, with input arrow entering at the bottom and output arrow exiting at the top, plus a legend distinguishing trainable prefix from frozen weights.
Layer-specific prefix injection within a transformer architecture. Each layer receives distinct learned prefix vectors for keys and values, letting task-specific guidance at every abstraction level while keeping base weights frozen. This hierarchy allows the model to adjust syntax in early layers and semantics in later stages.

The Reparameterization Trick

Directly optimizing the prefix matrices often leads to unstable training. The loss surface can be non-convex, and the prefixes can drift to regions that cause attention weights to saturate or vanish. This instability occurs because the prefix vectors interact with the attention mechanism in nonlinear ways. Recall that attention weights are computed via softmax over dot products of queries and keys. Small changes to key values can produce large changes in attention probabilities when the softmax operates near saturation. A key vector that becomes very large in magnitude will dominate all attention weights, causing the model to ignore all real input tokens and attend only to that virtual token. Conversely, key vectors with small magnitudes will be ignored entirely.

To address this challenge, Li and Liang proposed a reparameterization using a small feed-forward network. The reason is that instead of directly optimizing the high-dimensional prefix vectors in their raw form, we can learn a more compact representation and project it into the required space. This bottleneck structure constrains the optimization to a lower-dimensional subspace, regularizing the solution and smoothing the loss surface. Instead of optimizing layer-specific prefixes directly, we learn a single smaller matrix PθP_{\theta} and project it through an MLP to generate prefixes for all layers:

{PK(l),PV(l)}l=1L=Split(MLP(Pθ))\{P_K^{(l)}, P_V^{(l)}\}_{l=1}^L = \text{Split}(\text{MLP}(P_{\theta}))

where:

  • PθP_{\theta}: the learnable matrix of shape m×d′m \times d' (where d′≪dd' \ll d), shared across all layers as a compressed task representation
  • MLP\text{MLP}: a feed-forward network with a hidden layer, projecting the low-dimensional PθP_{\theta} to the combined dimensionality required for all layer prefixes
  • Split\text{Split}: an operation that divides the large MLP output into 2L2L individual matrices, one PK(l)P_K^{(l)} and one PV(l)P_V^{(l)} per layer
  • PK(l)P_K^{(l)}: the resulting prefix key matrix for layer ll, of shape m×dkm \times d_k
  • PV(l)P_V^{(l)}: the resulting prefix value matrix for layer ll, of shape m×dvm \times d_v

The MLP projects the shared PθP_{\theta} from the compressed representation space to the high-dimensional space required for all layers. During training, we optimize PθP_{\theta} and the MLP weights rather than the final prefix vectors directly. The total parameter count for the trainable component is determined by the MLP architecture and the compressed dimension d′d', not by the full 2Ld⋅m2Ld \cdot m product that we would need if optimizing directly.

A necessary practical benefit: after training, we can discard the MLP entirely. We simply compute the final prefix values by running PθP_{\theta} through the trained MLP once, storing the resulting PK(l)P_K^{(l)} and PV(l)P_V^{(l)} matrices. At inference time, we use these precomputed matrices directly. The MLP is only needed during training; it is a smooth parameterization that makes optimization more stable, after which it is no longer required.

The MLP typically has one hidden layer with a nonlinear activation:

MLP(x)=tanh⁡(xW1+b1)W2+b2\text{MLP}(x) = \tanh(xW_1 + b_1)W_2 + b_2

where:

  • xx: a row vector from the prefix matrix PθP_{\theta}, with dimension d′d'
  • W1W_1: weight matrix of the first linear layer, of shape d′×dhiddend' \times d_{\text{hidden}}, performing an initial transformation
  • b1b_1: bias vector of the first linear layer, of dimension dhiddend_{\text{hidden}}
  • tanh⁡\tanh: the hyperbolic tangent nonlinear activation, bounding outputs to [−1,1][-1, 1]
  • W2W_2: weight matrix of the second linear layer, of shape dhidden×doutd_{\text{hidden}} \times d_{\text{out}}, projecting to the full prefix dimension
  • b2b_2: bias vector of the second linear layer, of dimension doutd_{\text{out}}

The hyperbolic tangent activation is particularly well-suited here because it bounds outputs to the range [−1,1][-1, 1], preventing the prefix values from growing arbitrarily large during training. This bounded activation helps maintain numerical stability throughout the optimization process. In contrast, using a ReLU activation could allow prefix values to grow unboundedly during gradient descent, potentially causing the attention saturation problems we are trying to avoid.

This reparameterization gives several important benefits:

  • Training stability: The MLP constrains the prefix space, preventing extreme values that could cause attention saturation and vanishing gradients
  • Better generalization: The bottleneck dimension d′d' acts as regularization, encouraging the model to learn compact, generalizable representations rather than overfitting to training data
  • Smoother optimization: Gradients flow through the MLP with better conditioning, giving a more favorable loss surface with fewer sharp local minima and saddle points
  • Reduced effective dimensionality: The number of degrees of freedom in the optimization is m×d′m \times d' plus MLP parameters, rather than the full 2L×m×d2L \times m \times d, making the optimization problem more tractable

Parameter Count

The total number of trainable parameters in prefix tuning depends on prefix length mm, model dimension dd, number of layers LL, and the reparameterization architecture. Understanding this count helps us compare prefix tuning's efficiency against other methods and plan resource requirements.

Without reparameterization, the inference-time parameter count is the sum of all elements in the layer-specific prefix matrices:

Paramsinference=2×m×d×L\text{Params}_{\text{inference}} = 2 \times m \times d \times L

where:

  • mm: prefix length (number of virtual tokens)
  • dd: model hidden dimension
  • LL: number of transformer layers
  • 22: factor for separate key and value prefixes at each layer

The factor of 2 accounts for the fact that we learn independent prefix matrices for both keys and values at each layer. Each of these matrices has mm rows (one per prefix position) and dd columns (matching the model's hidden dimension, assuming dk=dv=dd_k = d_v = d for simplicity).

For a model like GPT-2 Medium with L=24L = 24 layers and d=1024d = 1024, a prefix length of m=10m = 10 yields:

Params=2×m×d×L=2×10×1024×24=491,520 parameters\begin{aligned} \text{Params} &= 2 \times m \times d \times L \\ &= 2 \times 10 \times 1024 \times 24 \\ &= 491{,}520 \text{ parameters} \end{aligned}

This is roughly 0.1% of GPT-2 Medium's 345 million parameters. Learning fewer than half a million parameters can substantially alter the behavior of a model with hundreds of millions of frozen parameters. This efficiency lets practical fine-tuning even in resource-constrained environments and allows a single base model to serve many different tasks simultaneously, each with its own lightweight prefix stored separately.

For training with reparameterization, we add the MLP parameters. If the compressed dimension is d′=512d' = 512 and the hidden dimension is dhidden=512d_{\text{hidden}} = 512, and the output dimension is dout=2×L×dd_{\text{out}} = 2 \times L \times d, then:

ParamsMLP=m×d′+d′×dhidden+dhidden×dout+biases\text{Params}_{\text{MLP}} = m \times d' + d' \times d_{\text{hidden}} + d_{\text{hidden}} \times d_{\text{out}} + \text{biases}

For GPT-2 Medium with m=10m = 10, d′=512d' = 512, dhidden=512d_{\text{hidden}} = 512, L=24L = 24, d=1024d = 1024, this adds roughly 512×512+512×(2×24×1024)≈25512 \times 512 + 512 \times (2 \times 24 \times 1024) \approx 25 million training-only parameters. These are discarded at inference, so the inference overhead remains the small 491,520491,520 from the prefix matrices themselves.