Prefix Tuning › The Prefix Tuning Formulation
Language AI HandbookAll chapters 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:
where:
- : the query matrix, containing row vectors representing "what we are looking for" at each sequence position
- : the key matrix, containing row vectors representing "what each position offers" for matching
- : the value matrix, containing row vectors with "what we retrieve" when a match is found
- : the dimension of the key vectors, used as a scaling factor
- : the function converting raw attention scores into a probability distribution over positions
We scale by 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 -dimensional space, if and contain random unit vectors, the expected magnitude of their dot product is . Without the scaling factor, attention scores for a model with would be roughly 32 times larger than for one with , causing the softmax to become nearly one-hot (peaking sharply at the highest score) and preventing smooth gradient flow. Dividing by 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 :
where:
- : the input sequence matrix of shape , with one row per token and columns per model dimension
- : the learnable query projection matrix, mapping from -dimensional input to -dimensional query space
- : the learnable key projection matrix, mapping from -dimensional input to -dimensional key space
- : the learnable value projection matrix, mapping from -dimensional input to -dimensional value space
This formulation reveals two potential ways to adapt model behavior. We could modify the projection matrices , , and , 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 real input positions and the 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 and be learnable prefix matrices, where is the prefix length. The modified attention becomes:
where:
- : the extended key matrix of shape
- : the extended value matrix of shape
- : learnable prefix matrix of shape , containing the virtual key vectors
- : learnable prefix matrix of shape , containing the virtual value vectors
- : original key matrix of shape , derived from the real input
- : original value matrix of shape , 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 key positions and to these 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:
where:
- : the query matrix of shape (unchanged, derived only from real input tokens)
- : the extended key matrix of shape
- : the extended value matrix of shape
- : the key dimension, used as the scaling factor
- : now normalizes over positions rather than the original
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 matrix, one row per real input token. The prefixes influence computation by giving additional things to attend to, not additional positions that produce outputs.

The prefix vectors and 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 layers, prefix tuning learns a complete set of layer-specific prefix matrices:
where:
- : learnable prefix matrices for the -th transformer layer, each of shape and respectively
- : 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 does not need to survive unchanged through layers of transformation; instead, it gives appropriate guidance at exactly the point in processing where that guidance is needed.

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 and project it through an MLP to generate prefixes for all layers:
where:
- : the learnable matrix of shape (where ), shared across all layers as a compressed task representation
- : a feed-forward network with a hidden layer, projecting the low-dimensional to the combined dimensionality required for all layer prefixes
- : an operation that divides the large MLP output into individual matrices, one and one per layer
- : the resulting prefix key matrix for layer , of shape
- : the resulting prefix value matrix for layer , of shape
The MLP projects the shared from the compressed representation space to the high-dimensional space required for all layers. During training, we optimize 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 , not by the full 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 through the trained MLP once, storing the resulting and 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:
where:
- : a row vector from the prefix matrix , with dimension
- : weight matrix of the first linear layer, of shape , performing an initial transformation
- : bias vector of the first linear layer, of dimension
- : the hyperbolic tangent nonlinear activation, bounding outputs to
- : weight matrix of the second linear layer, of shape , projecting to the full prefix dimension
- : bias vector of the second linear layer, of dimension
The hyperbolic tangent activation is particularly well-suited here because it bounds outputs to the range , 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 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 plus MLP parameters, rather than the full , making the optimization problem more tractable
Parameter Count
The total number of trainable parameters in prefix tuning depends on prefix length , model dimension , number of layers , 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:
where:
- : prefix length (number of virtual tokens)
- : model hidden dimension
- : number of transformer layers
- : 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 rows (one per prefix position) and columns (matching the model's hidden dimension, assuming for simplicity).
For a model like GPT-2 Medium with layers and , a prefix length of yields:
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 and the hidden dimension is , and the output dimension is , then:
For GPT-2 Medium with , , , , , this adds roughly million training-only parameters. These are discarded at inference, so the inference overhead remains the small from the prefix matrices themselves.