AI Wiki中文/EN

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.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

A 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.

A nonlinear residual adapter fits a curved target that the best affine map cannot exactly represent.
A nonlinear residual adapter fits a curved target that the best affine map cannot exactly represent.

Keep the identity path and learn the correction

For column vector h∈Rdh\in\mathbb R^d, bottleneck width mm, down-projection D∈Rm×dD\in\mathbb R^{m\times d} and up-projection U∈Rd×mU\in\mathbb R^{d\times m}, one residual adapter is:

f(h)=h+Uϕ(Dh+bd)+bu.f(h)=h+U\phi(Dh+b_d)+b_u.

The biases have dimensions mm and dd. This article uses ϕ=tanh⁡\phi=\tanh. 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:

Pmodule=2dm+m+d.P_{\mathrm{module}}=2dm+m+d.

At d=768,m=64d=768,m=64, one module has 99,136 parameters. Two modules per Transformer block double that contribution; normalization and task heads must be added separately. In our d=2,m=1d=2,m=1 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:

Jf(h)=Id+Udiag⁡ ⁣(1−tanh⁡2(Dh+bd))D.J_f(h)=I_d+U\operatorname{diag}\!\left(1-\tanh^2(Dh+b_d)\right)D.

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 mm; that local statement does not turn the global nonlinear function into one low-rank matrix.

For row-oriented examples HH and targets YY, our regression objective is:

L=12N∑n=1N∥f(hn)−yn∥22.\mathcal L=\frac1{2N}\sum_{n=1}^{N}\|f(h_n)-y_n\|_2^2.

Let Z=HD⊤+1bd⊤Z=HD^\top+\mathbf1 b_d^\top, V=tanh⁡ZV=\tanh Z, and let EE be the matrix of output errors divided by NN. Then:

∂L∂U=E⊤V,∂L∂bu=∑nEn.\frac{\partial\mathcal L}{\partial U}=E^\top V,\qquad \frac{\partial\mathcal L}{\partial b_u}=\sum_n E_n.

Backpropagate through the bottleneck with R=(EU)⊙(1−V2)R=(EU)\odot(1-V^2), where ⊙\odot is elementwise multiplication:

∂L∂D=R⊤H,∂L∂bd=∑nRn.\frac{\partial\mathcal L}{\partial D}=R^\top H,\qquad \frac{\partial\mathcal L}{\partial b_d}=\sum_n R_n.

Our program initializes DD randomly at small scale and sets U,bd,buU,b_d,b_u to zero. The initial map is exactly the identity. The first DD gradient is zero, but UU can receive a gradient through the nonzero bottleneck features; bub_u 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 gg satisfies:

g(a+b)−g(a)−g(b)+g(0)=0.g(a+b)-g(a)-g(b)+g(0)=0.

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 (1,−0.5)(1,-0.5), up-projection (0.8,−0.6)⊤(0.8,-0.6)^\top, down bias 0.2 and output bias (0.1,−0.2)(0.1,-0.2). After 2,500 gradient steps, training loss is approximately 6.86×10−86.86\times10^{-8} and 49-point grid loss approximately 4.88×10−84.88\times10^{-8}. The best affine training loss is about 0.00562419. These are squared losses under the displayed normalization, not classification accuracies.

For a=(0.8,0.1)a=(0.8,0.1) and b=(−0.2,0.7)b=(-0.2,0.7), 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 O(dm)O(dm) arithmetic per token and O(dm+d+m)O(dm+d+m) 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

  1. What happens if U=0U=0 and bu=0b_u=0? 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.
  2. How many parameters does one module with d=768,m=64d=768,m=64 contain, including biases? Answer: 2(768)(64)+768+64=99,1362(768)(64)+768+64=99,136. Add any other modules, normalization parameters and task head separately.
  3. 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.
  4. 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?

Choose one answer

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

  1. Parameter-Efficient Transfer Learning for NLP
    Neil Houlsby; Andrei Giurgiu; Stanislaw Jastrzebski; Bruna Morrone; Quentin De Laroussilhe; Andrea Gesmundo; Mona Attariyan; Sylvain Gelly · 2019
  2. 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:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.