Adapters: change hidden states through a narrow residual path
Adapter 微调
Train a nonlinear bottleneck, derive its Jacobian and test why it cannot generally merge into one affine layer.
adaptersA narrow detour can change a wide representation
A hidden vector need not pass through a completely retrained network to change its behavior. An adapter can send that vector through a narrow projection, apply a nonlinearity, project back and add the result to the original vector. At initialization the detour can contribute almost nothing; after training it can make an input-dependent correction.
That nonlinearity is consequential. In our two-dimensional experiment, a seven-parameter adapter fits a curved target almost exactly, while the best affine map retains a measurable error. There is no single fixed weight matrix that reproduces every such nonlinear correction.
Houlsby and colleagues propose bottleneck adapters for language-model transfer. Their Transformer configuration also trains task-specific layer-normalization parameters and a classifier; “only the adapter learns” would omit part of that recipe. LoRA provides a useful comparison because its additive linear update can instead be merged into a weight matrix under suitable inference conditions.
Keep the identity path and learn the correction
For column vector , bottleneck width , down-projection and up-projection , one residual adapter is:
The biases have dimensions and . This article uses . The formula describes one adapter module, not the surrounding Transformer’s attention, feed-forward block, outer residual and layer normalization.
Including these two biases, its parameter count is:
At , one module has 99,136 parameters. Two modules per Transformer block double that contribution; normalization and task heads must be added separately. In our toy the count is seven, more than the four entries of a two-by-two matrix. The toy demonstrates mechanism, not a favorable compression ratio.
The module’s input Jacobian for tanh is:
The identity path remains, but the added derivative changes with the input. A residual connection does not make the whole function linear. Each local Jacobian correction has rank at most ; that local statement does not turn the global nonlinear function into one low-rank matrix.
For row-oriented examples and targets , our regression objective is:
Let , , and let be the matrix of output errors divided by . Then:
Backpropagate through the bottleneck with , where is elementwise multiplication:
Our program initializes randomly at small scale and sets to zero. The initial map is exactly the identity. The first gradient is zero, but can receive a gradient through the nonzero bottleneck features; can also move. This is an explicit teaching initialization. Houlsby’s paper describes near-zero projections and an approximately identity module, which is not the same as requiring our exact choice.
Any affine function satisfies:
Finding a nonzero result for an adapter disproves that it equals any single affine map on all inputs. If the activation were identity instead, the projections and biases could be combined algebraically; the nonlinearity is what makes the general case different.
Compare with the best affine baseline
The complete NumPy example keeps an identity backbone fixed and trains one tanh adapter on nine grid points. A declared teacher adapter generates the targets. An affine least-squares fit supplies a meaningful simpler baseline; a separate 49-point grid tests interpolation beyond the training points.
"""Train one residual tanh bottleneck; frozen identity backbone, synthetic target."""
import json
import numpy as np
def initialize(seed=31,zero_up=True):
rng=np.random.default_rng(seed)
return dict(d=rng.normal(0,.1,(1,2)),u=np.zeros((2,1)) if zero_up else rng.normal(0,.1,(2,1)),bd=np.zeros(1),bu=np.zeros(2))
def forward(p,x):
z=x@p['d'].T+p['bd'];h=np.tanh(z)
return x+h@p['u'].T+p['bu'],h
def objective(p,x,y):
pred,h=forward(p,x);err=pred-y;g=err/len(x);hidden=(g@p['u'])*(1-h*h)
return float(np.sum(err**2)/(2*len(x))),dict(d=hidden.T@x,u=g.T@h,bd=hidden.sum(axis=0),bu=g.sum(axis=0))
def teacher():return dict(d=np.array([[1.,-.5]]),u=np.array([[.8],[-.6]]),bd=np.array([.2]),bu=np.array([.1,-.2]))
def jacobian(p,x):
h=np.tanh(p['d']@x+p['bd']);return np.eye(len(x))+p['u']@np.diag(1-h*h)@p['d']
def train(steps=2500):
if type(steps) is not int or not 0<=steps<=10000:raise ValueError('Bounded integer steps required')
x=np.array([(a,b) for a in [-1.,0.,1.] for b in [-1.,0.,1.]])
y,_=forward(teacher(),x);p=initialize();history=[]
for i in range(steps+1):
loss,g=objective(p,x,y)
if i%250==0 or i==steps:history.append(dict(step=i,loss=loss))
if i<steps:
for k in p:p[k]-=.15*g[k]
return p,x,y,history
def demo():
p,x,y,history=train();grid=np.array([(a,b) for a in np.linspace(-1,1,7) for b in np.linspace(-1,1,7)]);truth,_=forward(teacher(),grid);prediction,_=forward(p,grid)
design=np.c_[x,np.ones(len(x))];affine=np.linalg.lstsq(design,y,rcond=None)[0]
points=np.array([[0.,0.],[.8,.1],[-.2,.7],[.6,.8]]);v,_=forward(p,points)
return dict(parameters={k:a.tolist() for k,a in p.items()},trace=history,trainable=sum(v.size for v in p.values()),large_module_parameters=2*768*64+768+64,grid_loss=float(np.sum((prediction-truth)**2)/(2*len(grid))),affine_training_loss=float(np.sum((design@affine-y)**2)/(2*len(x))),nonaffinity=float(np.linalg.norm(v[3]-v[1]-v[2]+v[0])),scope='One tanh residual module; no layer norm or task head; seven parameters on2D toy do not imply savings versus four backbone entries')
if __name__=='__main__':print(json.dumps(demo(),allow_nan=False))
The teacher uses down-projection , up-projection , down bias 0.2 and output bias . After 2,500 gradient steps, training loss is approximately and 49-point grid loss approximately . The best affine training loss is about 0.00562419. These are squared losses under the displayed normalization, not classification accuracies.
For and , the norm of the learned adapter’s affine-identity residual is approximately 0.173170. This directly rules out a globally equivalent affine merge for this trained function. It does not claim that every possible adapter is nonlinear: zero or otherwise degenerate parameters can produce affine maps.
Tests compare every parameter gradient and the full input Jacobian with central finite differences. They check the initial identity, first-step gradient asymmetry, module counts, deterministic initialization and the interpolation-grid result. This grid includes all nine training points among its 49 points, so it is not a disjoint held-out set. The lower-level helpers assume compatible finite matrix shapes; the example is not a general model-serving validator.
One module adds arithmetic per token and parameter storage. Training also needs activations and propagation through the fixed backbone. In a deep model, insertion location and number of modules affect both learning and inference cost; parameter count alone does not measure latency.
State exactly what is frozen and what is inserted
Houlsby’s configuration places adapters after the attention output projection and feed-forward projection, before the corresponding outer residual addition and subsequent normalization. Each adapter also has its own internal skip connection. Mixing these two residual paths changes the architecture.
Task-specific normalization and the final classifier are trained in that configuration. Other adapter variants use different placements, parallel paths or parameter-sharing rules. The word “adapter” can also be used broadly for parameter-efficient methods; this chapter specifically concerns bottleneck residual modules.
Freezing a shared backbone prevents its weights from drifting across tasks, but does not automatically solve routing, label conventions, distribution shift or conflicts in shared trainable components. Swapping the wrong task module still gives the wrong adapted function. Our synthetic teacher is exactly within the model class, so the small error is not evidence of universal adaptation capacity.
Inspect the path, not just the parameter count
- What happens if and ? Answer: The adapter output equals its input regardless of the bottleneck values. This creates an identity initialization; it does not mean all parameter gradients vanish.
- How many parameters does one module with contain, including biases? Answer: . Add any other modules, normalization parameters and task head separately.
- Why does a nonzero value of the affine-identity residual disprove a fixed affine merge? Answer: Every affine map satisfies the identity for every pair of inputs. One counterexample is enough to show the trained function is not globally affine.
- Does freezing the backbone remove the need to differentiate through it? Answer: No. Earlier adapters can require gradients transmitted through later frozen operations. Parameter updates and derivatives with respect to intermediate states are different requirements.
Insertion and parameterization answer different questions
Houlsby’s work studies a small bottleneck inserted into an existing architecture. Hu and colleagues study a low-rank increment to an existing weight. Both can reduce task-specific storage in large models, but their function classes and inference paths differ.
Compare them with the same base, data and evaluation before attributing an advantage to one mechanism. Our affine baseline and Jacobian check isolate the bottleneck’s nonlinear effect; they do not reproduce BERT transfer results or device timing.
Make a prediction, then check
Can a nonlinear bottleneck adapter always be merged into one fixed affine weight?
Learning objectives
- Trace the down-projection, nonlinearity, up-projection and residual.
- Count module, normalization and task-head parameters separately.
- Explain why a nonlinear adapter generally cannot be weight-merged.
Prerequisites & connections
Explore related knowledge →References
- Parameter-Efficient Transfer Learning for NLP
Neil Houlsby; Andrei Giurgiu; Stanislaw Jastrzebski; Bruna Morrone; Quentin De Laroussilhe; Andrea Gesmundo; Mona Attariyan; Sylvain Gelly · 2019 - LoRA: Low-Rank Adaptation of Large Language Models — v2
Edward J. Hu; Yelong Shen; Phillip Wallis; Zeyuan Allen-Zhu; Yuanzhi Li; Shean Wang; Lu Wang; Weizhu Chen · 2021
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-20 · Single AI author viewed Houlsby ICML2019 PDF2/3 Figure2 and sections2/2.1, plus LoRA v2 PDF4/5. Seven paired equations and four explained exercises. Original trained tanh residual, all parameter/input derivatives, exact initial identity, affine least-squares baseline,49-point grid and nonaffinity counterexample. Distinguishes module/internal skip from outer residual and additional LayerNorm/head; no BERT replication.
- Single AI author viewed Houlsby ICML2019 PDF2/3 Figure2 and sections2/2.1, plus LoRA v2 PDF4/5. Seven paired equations and four explained exercises. Original trained tanh residual, all parameter/input derivatives, exact initial identity, affine least-squares baseline,49-point grid and nonaffinity counterexample. Distinguishes module/internal skip from outer residual and additional LayerNorm/head; no BERT replication.
- Four computed SVG variants per topic;11 numeric/geometry tests and36 responsive cases passed. Twelve selected captures checked:seven final directly viewed,five byte-identical to previously viewed images. Full article acceptance recorded separately.
- Post-freeze wording correction after inspecting the actual3x3 training grid and7x7 evaluation grid:all9 training points occur among49 evaluation points. Call it an interpolation grid, not a disjoint held-out set. Both languages corrected; new overlap test added; original candidate retained. Numerical results, program and figures unchanged.
Source locations checked:
- Parameter-Efficient Transfer Learning for NLP · Read and viewed PDF2/3: section2/2.1, Figure2, bottleneck placement, internal skip, near-identity initialization, additional layer-norm/task-head training. No BERT benchmark reproduction.
- LoRA: Low-Rank Adaptation of Large Language Models — v2 · Read and viewed PDF4/5: sections4.1/4.2, BA update, randomA/zeroB, alpha/r, merging and frozen/adapted weights. Benchmark tables not reproduced.
Related topics