Sam Babichenko

Reading notes / In-context learning

Transformers Learn In-Context by Gradient Descent

von Oswald et al., 2023; Ahn et al., 2023; Zhang et al., 2024

Context. Transformers trained on random linear-regression prompts predict about as well as least squares (Garg et al.), which says nothing about mechanism. Three papers settle the one-layer case: von Oswald et al. build a linear attention layer that takes one gradient-descent step on the prompt and find it in trained weights, Ahn et al. show that the global minimum is such a step with a learned preconditioner, and Zhang et al. prove that gradient flow reaches it and compute its risk on any prompt. A linear attention layer adds ∑iviki⊤q\sum_iv_ik_i^\top q, a sum of outer products of the data with itself, which is the form of the squared-loss gradient for a linear model, so a trained layer predicts xquery⊤Γ−11M∑iyixix_{\rm query}^\top\Gamma^{-1}\frac1M\sum_iy_ix_i with Γ=(1+1N)Λ+trΛNI\Gamma=(1+\frac1N)\Lambda+\frac{\mathrm{tr}\Lambda}NI frozen at training time. That is a ridge-like smoother with shrinkage tr(Λ)/N\mathrm{tr}(\Lambda)/N set by the training prompt length, and because its preconditioner is learned from the training covariates instead of computed from the prompt, it tolerates shifts in the task and the query but not in the covariates.

Setting. Each example is one token ej=(xj,yj)e_j=(x_j,y_j), and the query token starts as (xquery,0)(x_{\rm query},0) and holds the prediction in its yy-entry at the end. Linear self-attention (LSA) is attention with the softmax removed, ej←ej+PWV(∑ieiei⊤)WK⊤WQ ej,e_j\leftarrow e_j+PW_V\Big(\sum_{i}e_ie_i^\top\Big)W_K^\top W_Q\,e_j, and only the products PWVPW_V and WK⊤WQW_K^\top W_Q matter, up to the rescaling (sPWV,WK⊤WQ/s)(sPW_V,W_K^\top W_Q/s). Training draws a fresh task w∼N(0,Id)w\sim N(0,I_d) for each prompt, inputs xi,xquery∼N(0,Λ)x_i,x_{\rm query}\sim N(0,\Lambda) with eigenvalues λi\lambda_i, and noiseless labels yi=w⊤xiy_i=w^\top x_i, and minimizes the squared error at the query over prompts of length NN; a test prompt has length MM. Ahn et al. keep the query out of the keys and values and Zhang et al. let it in; the predictor is the same.

Step 1

A gradient step is a change of targets, and one attention layer makes it (von Oswald et al.). Push the update from the weights into the data: for ΔW=−ηN∑i(Wxi−yi)xi⊤\Delta W=-\frac\eta N\sum_i(Wx_i-y_i)x_i^\top, L(W+ΔW)=12N∑i∥Wxi−(yi−ΔWxi)∥2,L(W+\Delta W)=\frac1{2N}\sum_i\big\|Wx_i-(y_i-\Delta Wx_i)\big\|^2, so a layer that subtracts ΔWxj\Delta Wx_j from every token's yy-entry, the query included, has taken the step without ever storing WW. With WK⊤WQW_K^\top W_Q picking out xi⊤xjx_i^\top x_j, WVW_V sending eie_i to (0,W0xi−yi)(0,W_0x_i-y_i) and P=ηNIP=\frac\eta NI, the attention sum is exactly that update; starting the query at (xquery,−W0xquery)(x_{\rm query},-W_0x_{\rm query}) and negating its yy-entry at the end reads out (W0+ΔW)xquery(W_0+\Delta W)x_{\rm query}. From W0=0W_0=0 the prediction is ηN∑iyixi⊤xquery\frac\eta N\sum_iy_ix_i^\top x_{\rm query}, Garg's averaging estimator up to η\eta.

Step 2

Stacking gives more steps, and one more block adds curvature correction. After a layer the context tokens hold the residuals yi−ΔW1xiy_i-\Delta W_1x_i, the data the updated model faces, so KK layers are KK GD steps. GD++ also moves every input, the query included, by x←(I−γXX⊤)xx\leftarrow(I-\gamma XX^\top)x, which replaces the Hessian H=XX⊤H=XX^\top by H++=(I−γH)H(I−γH),λ↦λ(1−γλ)2.H^{++}=(I-\gamma H)H(I-\gamma H),\qquad\lambda\mapsto\lambda(1-\gamma\lambda)^2 . The gain depends on γ\gamma: for γ≤1/(3λmax⁡)\gamma\le1/(3\lambda_{\max}) the map is increasing on the spectrum and the condition number falls, larger γ\gamma maps the top of the spectrum to values below the peak at 1/(3γ)1/(3\gamma), which can help more, and γ\gamma near 1/λmax⁡1/\lambda_{\max} makes it worse. Repeated over layers it is an iterative preconditioner computed from the prompt.

Step 3

An MLP supplies features, and an earlier head builds the tokens. After a residual MLP mm the same layer takes GD steps on kernel regression with k(x,x′)=m(x)⊤m(x′)k(x,x')=m(x)^\top m(x'). When inputs and targets sit in separate tokens, a head whose key-query product selects the successor's positional encoding copies each yjy_j into its xjx_j token, as an induction head does, and the next layer takes the GD step, as trained two-layer models do. Through a softmax the copy is only approximate (weight e/(e+2N)e/(e+2N) on the successor among 2N+12N+1 tokens), so the key-query product must be scaled up.

Step 4

Trained models match the construction (experiments). A trained single LSA layer matches one tuned GD step in loss, predictions and input sensitivities, its rescaled matrices visibly match the construction, and the midpoint of trained and constructed weights has the same loss. The two fail together: for inputs from U(−α,α)U(-\alpha,\alpha) with α>1\alpha\gt1 both blow up, because a step size tuned for α=1\alpha=1 overshoots the higher curvature. The match needs task diversity (it fails at 128 training tasks and is nearly perfect above 2048). Deeper models drift toward GD++, but only with fitted η,γ\eta,\gamma per layer, which is weaker evidence.

Step 5

The one-layer loss is a sum of convex functions of rank-one matrices, and a convex relaxation solves it (Ahn et al.). For Gaussian inputs the global minimizer predicts xquery⊤Γ−11N∑iyixix_{\rm query}^\top\Gamma^{-1}\frac1N\sum_iy_ix_i, one step from zero of GD preconditioned by Γ−1\Gamma^{-1}; for Λ=I\Lambda=I, Γ−1=NN+d+1I\Gamma^{-1}=\frac N{N+d+1}I, plain GD with a tuned step, von Oswald's construction. The loss is nonconvex, so the proof relaxes it. With the query masked, the prediction is −b⊤GAxquery-b^\top GAx_{\rm query}, where GG is the second-moment matrix of the context tokens, b⊤b^\top the last row of the value-projection product and AA the first dd columns of the key-query product, and for Λ=I\Lambda=I the loss splits over the columns aja_j of AA: f(b,A)=∑j=1dfj(baj⊤),fj(X)=E[⟨G,X⟩+w[j]]2.f(b,A)=\sum_{j=1}^df_j(ba_j^\top),\qquad f_j(X)=\mathbb E\big[\langle G,X\rangle+w[j]\big]^2 . Each fjf_j is a convex quadratic in XX; minimize it over all XX by Gaussian moments, and since the minimizers share one b=ed+1b=e_{d+1}, they solve the original problem (general Λ\Lambda follows by rotating). The trΛN\frac{\mathrm{tr}\Lambda}N in Γ\Gamma comes from the fourth moment E[∥x∥2xx⊤]\mathbb E[\|x\|^2xx^\top], the variance of 1N∑iyixi\frac1N\sum_iy_ix_i from having only NN samples, and it shrinks directions with λi≲tr(Λ)/N\lambda_i\lesssim\mathrm{tr}(\Lambda)/N as ridge would. The minimal loss is ∑iλi(λi+trΛ)/((N+1)λi+trΛ)\sum_i\lambda_i(\lambda_i+\mathrm{tr}\Lambda)/((N+1)\lambda_i+\mathrm{tr}\Lambda), which is d(d+1)/(N+d+1)d(d+1)/(N+d+1) for Λ=I\Lambda=I (a short computation, not in the paper, checked by simulation), so one layer never interpolates.

Step 6

With sparse layers the forward pass is preconditioned GD, and the loss is a matrix polynomial. Restrict each layer to a value product that writes only the label row and a key-query product −diag(Aℓ,0)-\mathrm{diag}(A_\ell,0). The inputs never change, the mask makes the query's label enter only additively, and every context label follows the same recursion as the query's, so by induction it holds the residual of the current model: θℓ+1=θℓ−1NAℓ⊤XˉXˉ⊤(θℓ+w),wℓgd=−θℓ,\theta_{\ell+1}=\theta_\ell-\tfrac1NA_\ell^\top\bar X\bar X^\top(\theta_\ell+w),\qquad w_\ell^{\rm gd}=-\theta_\ell, with Xˉ\bar X the context inputs: LL steps of GD with per-layer preconditioners. Putting the true label in the query slot turns the output into the prediction error, so the loss is an explicit matrix polynomial in the AℓA_\ell, built from X∏ℓ(I+MX⊤AℓX)X\prod_\ell(I+\mathcal MX^\top A_\ell X) with M\mathcal M the mask; the remaining results analyze that polynomial.

Step 7

For two layers some global minimizer is diagonal, by rotation and random sign flips. For L=2L=2, isotropic data and symmetric A1,A2A_1,A_2, some pair of diagonal matrices is a global minimizer, so the best two-layer model is GD with coordinatewise step sizes. Take a global minimizer, diagonalize A1∗A_1^* by rotation invariance, and conjugate A2A_2 by a random diagonal sign matrix SS: the loss is unchanged (SD1S=D1SD_1S=D_1, the data are sign-invariant) and convex in A2A_2, because the output is affine in A2A_2. Since ES[SA2S]=diag(A2)\mathbb E_S[SA_2S]=\mathrm{diag}(A_2), Jensen gives f(D1,diagA2∗)≤ESf(D1,SA2∗S)=f(A1∗,A2∗).f(D_1,\mathrm{diag}A_2^*)\le\mathbb E_Sf(D_1,SA_2^*S)=f(A_1^*,A_2^*) .

Step 8

At symmetric points the gradient can be matched inside the symmetric set, so it contains critical points. With prior w∼N(0,Λ−1)w\sim N(0,\Lambda^{-1}), Theorem 3 says the set S={Aℓ=aℓΛ−1}S=\{A_\ell=a_\ell\Lambda^{-1}\}, GD preconditioned by the Newton matrix, contains critical points, possibly approached only in the limit; Theorem 4 adds input updates bℓIb_\ell I, which give GD++ when Λ=I\Lambda=I; the input update commutes with the symmetry used below only when it is a multiple of II. The data law is invariant under X↦UΛXX\mapsto U_\Lambda X, UΛ=Λ1/2UΛ−1/2U_\Lambda=\Lambda^{1/2}U\Lambda^{-1/2} with UU Haar orthogonal, which fixes points of SS, so perturbing a layer in direction RR changes ff as perturbing it in direction UΛ⊤RUΛU_\Lambda^\top RU_\Lambda, and by linearity in the direction one may average: EU[UΛ⊤RUΛ]=1dtr(Λ1/2RΛ1/2) Λ−1.\mathbb E_U[U_\Lambda^\top RU_\Lambda]=\tfrac1d\mathrm{tr}(\Lambda^{1/2}R\Lambda^{1/2})\,\Lambda^{-1}. Every directional derivative at a point of SS is thus matched by one inside SS, so a flow constrained to SS decreases ff at rate at least the full squared gradient norm, and since f≥0f\ge0 the gradient cannot stay away from zero. This shows existence and says nothing about optimality, but Adam finds these points: in a trained three-layer model Λ1/2AℓΛ1/2\Lambda^{1/2}A_\ell\Lambda^{1/2} converges to multiples of II, and with input updates the whitened step sizes grow across layers (about −0.38,−2.40,−9.59-0.38,-2.40,-9.59) as the conditioning improves.

Step 9

With ReLU attention the minimizer is again a multiple of the identity, by sign symmetrization and Stein's lemma. With ReLU applied to the attention scores, isotropic data and the last row of the key-query product zero, the same rotation, sign-flip and Jensen moves bound the loss below by a function of b1Ab_1A, and Stein's lemma, E[σ(x⊤v)x]=v/2\mathbb E[\sigma(x^\top v)x]=v/2, evaluates every term: flower=N−1+2(d+2)4N ∥b1A∥F2+tr(b1A)+const,f_{\rm lower}=\frac{N-1+2(d+2)}{4N}\,\|b_1A\|_F^2+\mathrm{tr}(b_1A)+\text{const}, a convex quadratic minimized at −2NN−1+2(d+2)I-\frac{2N}{N-1+2(d+2)}I, where the bound is attained. ReLU changes only the constant.

Step 10

The prediction is a rank-one factorization, and off the cross entries the loss reduces to two blocks (Zhang et al.). From a small balanced start, WPV(0)=σ diag(0,1)W^{PV}(0)=\sigma\,\mathrm{diag}(0,1) and WKQ(0)=σ diag(ΘΘ⊤,0)W^{KQ}(0)=\sigma\,\mathrm{diag}(\Theta\Theta^\top,0) with ∥ΘΘ⊤∥F=1\|\Theta\Theta^\top\|_F=1, gradient flow on the population loss converges to a global minimum whenever σ2∥Γ∥opd<2\sigma^2\|\Gamma\|_{\rm op}\sqrt d\lt2 (Theorem 4.1). The prediction is an indefinite quadratic form u⊤Hτuu^\top H_\tau u in the vector uu of the weights that affect it, value weight times key-query weight, so the dynamics are those of a two-layer linear network. The cross entries stay at zero, since every term in their derivatives carries an odd power of the mean-zero task, and Γ\Gamma enters through the Wishart fourth moment of Λ^=1N∑ixixi⊤\hat\Lambda=\frac1N\sum_ix_ix_i^\top. Up to a constant the loss in the key-query block U11U_{11} and the value entry u−1u_{-1} is ℓ~(U11,u−1)=12tr(u−12 ΓΛU11ΛU11⊤−2u−1Λ2U11⊤).\tilde\ell(U_{11},u_{-1})=\tfrac12\mathrm{tr}\big(u_{-1}^2\,\Gamma\Lambda U_{11}\Lambda U_{11}^\top-2u_{-1}\Lambda^2U_{11}^\top\big).

Step 11

Completing the square gives the minima, and conserved balance picks one. Since Γ\Gamma and Λ\Lambda commute, ℓ~−min⁡ℓ~=12∥Γ1/2(u−1Λ1/2U11Λ1/2−ΛΓ−1)∥F2,\tilde\ell-\min\tilde\ell=\tfrac12\Big\|\Gamma^{1/2}\big(u_{-1}\Lambda^{1/2}U_{11}\Lambda^{1/2}-\Lambda\Gamma^{-1}\big)\Big\|_F^2, so the global minima are exactly the hyperbola u−1U11=Γ−1u_{-1}U_{11}=\Gamma^{-1}, all giving the same predictor. Multiplying the two flow equations by U11⊤U_{11}^\top and u−1u_{-1} gives ddt∥U11∥F2=ddtu−12\frac d{dt}\|U_{11}\|_F^2=\frac d{dt}u_{-1}^2, the conservation law of two-layer linear networks, so balance u−12=∥U11∥F2u_{-1}^2=\|U_{11}\|_F^2 holds for all time and pins the limit on the hyperbola at u−1=∥Γ−1∥F1/2u_{-1}=\|\Gamma^{-1}\|_F^{1/2}, U11=∥Γ−1∥F−1/2Γ−1U_{11}=\|\Gamma^{-1}\|_F^{-1/2}\Gamma^{-1}.

Step 12

A small start avoids the saddle at zero, and then a PL inequality gives convergence. The origin u−1=0u_{-1}=0 is a saddle with ℓ~=0\tilde\ell=0, and the condition on σ\sigma makes ℓ~(0)<0\tilde\ell(0)\lt0 (von Neumann's trace inequality), so u−1u_{-1} never reaches 0; with balance it stays above some c0>0c_0\gt0. Keeping only the U11U_{11}-gradient and comparing with the completed square, ∥∇ℓ~∥2≥μ (ℓ~−min⁡ℓ~),\|\nabla\tilde\ell\|^2\ge\mu\,(\tilde\ell-\min\tilde\ell), so the excess loss decays like e−μte^{-\mu t}, the flow has finite length, and the limit is a global minimum.

Step 13

The error is a bias-variance split for a fixed linear smoother. For a test prompt of length MM from any distribution with x∼N(0,Λ)x\sim N(0,\Lambda), aa the best linear predictor, Σ=Cov(xy)\Sigma=\mathrm{Cov}(xy) and g^=1M∑iyixi\hat g=\frac1M\sum_iy_ix_i, yquery−y^query=(yquery−xquery⊤a)+xquery⊤(I−Γ−1Λ)a−xquery⊤Γ−1(g^−Λa),y_{\rm query}-\hat y_{\rm query}=\big(y_{\rm query}-x_{\rm query}^\top a\big)+x_{\rm query}^\top(I-\Gamma^{-1}\Lambda)a-x_{\rm query}^\top\Gamma^{-1}(\hat g-\Lambda a), with vanishing cross terms. The last term is a variance 1Mtr(ΣΓ−2Λ)\frac1M\mathrm{tr}(\Sigma\Gamma^{-2}\Lambda), and I−Γ−1Λ=1NΓ−1(Λ+tr(Λ)I)I-\Gamma^{-1}\Lambda=\frac1N\Gamma^{-1}(\Lambda+\mathrm{tr}(\Lambda)I) gives a squared bias of order 1/N21/N^2 (Theorem 4.2). As for ridge, eigendirection ii keeps the fraction Nλi/((N+1)λi+trΛ)N\lambda_i/((N+1)\lambda_i+\mathrm{tr}\Lambda) of the signal, a shrinkage level tr(Λ)/N\mathrm{tr}(\Lambda)/N fixed at training, which does not vanish as MM grows. For noiseless tasks with w∼N(0,I)w\sim N(0,I) and κ\kappa the condition number of Λ\Lambda, the error is at most (d+1)trΛM+(1+2d+d2κ)trΛN2\frac{(d+1)\mathrm{tr}\Lambda}M+\frac{(1+2d+d^2\kappa)\mathrm{tr}\Lambda}{N^2}. The 1/M1/M term stays even for noiseless labels and M≫dM\gg d, because the model applies a fixed Γ−1\Gamma^{-1} where least squares would invert Λ^\hat\Lambda and be exact once M≥dM\ge d.

Step 14

The preconditioner fixed at training determines which distribution shifts the model tolerates. Any labels give the best linear predictor up to O(1/M+1/N2)O(1/M+1/N^2), so label noise and arbitrary ww are tolerated, and for small MM and isotropic Λ\Lambda a query orthogonal to all xix_i gets 0, as Garg et al. saw. Scaling the test inputs by cc gives y^≈c2xquery⊤w\hat y\approx c^2x_{\rm query}^\top w, Garg et al.'s input-scale failure, while least squares is unaffected. Training on random diagonal covariances, one per prompt, does not fix it, since one layer cannot form Λ^−1\hat\Lambda^{-1} and learns one fixed preconditioner: as M,N→∞M,N\to\infty it multiplies coordinate ii of ww by λnew,i E[λi2]/E[λi3]\lambda_{{\rm new},i}\,\mathbb E[\lambda_i^2]/\mathbb E[\lambda_i^3], which for Exponential(1) variances is λnew,i/3\lambda_{{\rm new},i}/3, right only when λnew,i=3\lambda_{{\rm new},i}=3.

Consequences and limits. For one linear attention layer the analysis is complete: the trained model is w^=Γ−11MX⊤y\hat w=\Gamma^{-1}\frac1MX^\top y, a linear estimator whose risk follows from the spectrum of Λ\Lambda. Training length acts as regularization, so test error has a floor of order 1/N21/N^2 however long the test prompt, and matching least squares in distribution does not make the model least squares: the learned preconditioner matches Garg et al.'s fragility to input scale and covariance, and only computing Λ^−1\hat\Lambda^{-1} from the prompt, which needs depth or nonlinearity, would remove it. The limits are linear attention, noiseless Gaussian training tasks, gradient flow on the population loss from one initialization, critical points without global optimality for depth, and softmax and LayerNorm variants that match less cleanly.

Terms

LSA layer
ej←ej+PWV(∑ieiei⊤)WK⊤WQeje_j\leftarrow e_j+PW_V\big(\sum_ie_ie_i^\top\big)W_K^\top W_Qe_j, softmax removed
Change of targets
L(W+ΔW)L(W+\Delta W) is the loss of WW on targets yi−ΔWxiy_i-\Delta Wx_i
KK layers
KK GD steps, since tokens carry residuals from layer to layer
GD++
GD plus x←(I−γXX⊤)xx\leftarrow(I-\gamma XX^\top)x each layer; eigenvalues λ(1−γλ)2\lambda(1-\gamma\lambda)^2
Γ=(1+1N)Λ+trΛNI\Gamma=(1+\frac1N)\Lambda+\frac{\mathrm{tr}\Lambda}NI
training-time preconditioner inverse; →Λ\to\Lambda as N→∞N\to\infty
Trained predictor
xquery⊤Γ−11M∑iyixix_{\rm query}^\top\Gamma^{-1}\frac1M\sum_iy_ix_i, preconditioned one-step GD
SS
symmetric parameters Aℓ=aℓΛ−1A_\ell=a_\ell\Lambda^{-1} (and bℓIb_\ell I); contains critical points
Balance
u−12=∥U11∥F2u_{-1}^2=\|U_{11}\|_F^2 is conserved by the flow; pins the limit
Error split
best linear error + O(1/M)+\ O(1/M) variance + O(1/N2)+\ O(1/N^2) shrinkage bias
Covariate scaling by cc
prediction ≈c2x⊤w\approx c^2x^\top w; least squares is unaffected

Quiz

  1. GD++ transforms inputs by x←(I−γXX⊤)xx\leftarrow(I-\gamma XX^\top)x. Why does this speed up learning?
  2. In Theorem 4.2 the excess error has a 1/M1/M term and a 1/N21/N^2 term. Which mechanism produces the 1/N21/N^2 term?
  3. Why does the error not vanish for noiseless linear test prompts with MM much larger than dd, as it would for least squares?
  4. Test inputs are scaled by cc while training used N(0,Λ)N(0,\Lambda). What does the trained model predict for large M,NM,N?

Sources