Sam Babichenko

Reading notes / In-context learning

Transformers as Statisticians

Bai et al., 2023

Context. Garg et al. showed that a transformer trained on random regression prompts predicts like least squares, and von Oswald et al. and Akyürek et al. built layers that take gradient steps on the prompt's squared loss. Missing was an end-to-end account: what accuracy a given depth and head count achieve, what risk follows, how many pretraining prompts find such weights, and how one network can run different procedures on different prompts. One attention layer is one gradient step on the prompt's empirical risk for any smooth convex loss, with the heads together approximating the loss derivative by a sum of ReLUs, and because convex gradient descent is non-expansive the per-layer errors only add. A few more layers can hold out part of the prompt, score the candidates and keep the best, so adaptivity, up to nearly Bayes-optimal prediction on a mixture of tasks, requires only a validation split and no new architecture.

Setting. Each token carries xix_i, yiy_i (0 for the query), scratch space and a flag tit_i (1 for training pairs, 0 for the query), and the prediction is read, clipped, from the query's output token. Attention uses a ReLU normalized by NN in place of softmax, and every layer is residual: h~i=hi+∑m=1M1N∑jσ(⟨Qmhi,Kmhj⟩) Vmhj.\tilde h_i=h_i+\sum_{m=1}^M\frac1N\sum_{j}\sigma\big(\langle Q_mh_i,K_mh_j\rangle\big)\,V_mh_j . One definition captures what heads can compute: gg is (ε,R,M,C)(\varepsilon,R,M,C)-approximable by sum of ReLUs if sup⁡∣g(z)−∑m≤Mcmσ(am⊤[z;1])∣≤ε\sup|g(z)-\sum_{m\le M}c_m\sigma(a_m^\top[z;1])|\le\varepsilon on [−R,R]k[-R,R]^k with ∑∣cm∣≤C\sum|c_m|\le C and ∥am∥1≤1\|a_m\|_1\le1. Mildly smooth functions qualify with modest (M,C)(M,C), and piecewise-linear ones exactly. Data are bounded, ∥xi∥≤Bx\|x_i\|\le B_x, ∣yi∣≤By|y_i|\le B_y, unless Gaussian.

Results: in-context algorithms. Gradient descent on any convex loss whose derivative is a sum of ReLUs runs in context, one layer per step, with error linear in depth: L+1L+1 attention-only layers with MM heads store iterates with ∥w^ℓ−wGDℓ∥2≤ε ℓηBx\|\hat w^\ell-w^\ell_{GD}\|_2\le\varepsilon\,\ell\eta B_x on every prompt whose empirical risk is 2/η2/\eta-smooth on the ball of radius BwB_w and has a minimizer of norm at most Bw/2B_w/2 (Theorem 13). On a prompt with α≤λmin⁡(X⊤X/N)≤λmax⁡(X⊤X/N)≤β\alpha\le\lambda_{\min}(X^\top X/N)\le\lambda_{\max}(X^\top X/N)\le\beta, ⌈2κlog⁡(BxBw/(2ε))⌉+1\lceil2\kappa\log(B_xB_w/(2\varepsilon))\rceil+1 layers with at most 3 heads compute ridge to accuracy ε\varepsilon, κ=(β+λ)/(α+λ)\kappa=(\beta+\lambda)/(\alpha+\lambda), and so inherit its risk: for N≥O~(d)N\ge\tilde O(d), O(κlog⁡(κN/σ))O(\kappa\log(\kappa N/\sigma)) layers come within O~(dσ2/N)\tilde O(d\sigma^2/N) of the best linear predictor on every sub-Gaussian well-posed distribution, linear or not, and O(log⁡(1/ε))O(\log(1/\varepsilon)) layers within ε\varepsilon of the Bayes risk under w⋆∼N(0,Id/d)w_\star\sim N(0,I_d/d), where the Bayes predictor is ridge with λ=dσ2/N\lambda=d\sigma^2/N. GLMs, logistic regression included, need many heads (O~(ε−2)\tilde O(\varepsilon^{-2}) per layer; O(log⁡N)O(\log N) layers and O~(d3N)\tilde O(d^3N) heads give excess risk O(d/N)O(d/N)), and Lasso needs many layers (βBw2/ε+1\beta B_w^2/\varepsilon+1 layers, 2 heads; on an ss-sparse Gaussian model with N≥O(slog⁡(d/δ))N\ge O(s\log(d/\delta)), with probability 1−δ1-\delta, risk σ2[1+O(slog⁡(d/δ)/N)]\sigma^2[1+O(s\log(d/\delta)/N)]).

Results: selection and pretraining. Given KK predictors fitted on a training split, three more layers output a convex combination whose validation loss is within γ\gamma of the best, so for a convex risk L(f^)≤min⁡kL(fk)+2max⁡k∣L^val(fk)−L(fk)∣+γL(\hat f)\le\min_kL(f_k)+2\max_k|\hat L_{\rm val}(f_k)-L(f_k)|+\gamma (Proposition 15). For noisy linear models whose noise level is drawn from {σ1,…,σK}\{\sigma_1,\dots,\sigma_K\}, with w⋆∼N(0,Id/d)w_\star\sim N(0,I_d/d) and N≥0.1dN\ge0.1d, a transformer with O(σmin⁡−2log⁡(N/σmin⁡))O(\sigma_{\min}^{-2}\log(N/\sigma_{\min})) layers and O(K)O(K) heads is within O~(σmax⁡2σmin⁡−2/3(log⁡K/N)1/3)\tilde O(\sigma_{\max}^2\sigma_{\min}^{-2/3}(\log K/N)^{1/3}) of the Bayes risk of every component, hence of the mixture (Theorem 17). For pretraining, the empirical risk minimizer over nn prompts within the norm ball ΘL,M,D′,B\Theta_{L,M,D',B} (depth LL, MM heads, MLP width D′D', token dimension DD, norm at most BB) is, with probability 1−ξ1-\xi, within O(By2(L2(MD2+DD′)ι+log⁡(1/ξ))/n)O\big(B_y^2\sqrt{(L^2(MD^2+DD')\iota+\log(1/\xi))/n}\big) of the best in the ball, ι\iota logarithmic in the norms (Theorem 20); the constructions as comparators give polynomial prompt counts for ridge and the noise mixture.

Step 1

One attention layer takes one gradient step, one head per ReLU piece of the loss derivative. The query carries the current iterate ww (stored in every token), the key carries (xj,yj)(x_j,y_j), and the value the direction xjx_j: head mm scores am⟨w,xj⟩+bmyj+dma_m\langle w,x_j\rangle+b_my_j+d_m, with a key term that pushes the score below zero on the query token, and writes −ηcmxj-\eta c_mx_j into the ww-slot. Summed over heads the ReLUs rebuild the derivative, ∑mcm σ(am⟨w,xj⟩+bmyj+dm)≈∂sℓ(⟨w,xj⟩,yj),\sum_m c_m\,\sigma\big(a_m\langle w,x_j\rangle+b_my_j+d_m\big)\approx\partial_s\ell(\langle w,x_j\rangle,y_j), so the residual update is w−ηN∑j∂sℓ(⟨w,xj⟩,yj) xjw-\frac\eta N\sum_j\partial_s\ell(\langle w,x_j\rangle,y_j)\,x_j up to an error of norm εηBx\varepsilon\eta B_x. This determines the head count. The squared loss needs two heads, since s−y=2σ((s−y)/2)−2σ(−(s−y)/2)s-y=2\sigma((s-y)/2)-2\sigma(-(s-y)/2), an ℓ2\ell_2 penalty one more, and a smooth loss as many as its sum-of-ReLUs approximation. A final 2-head layer reads out ⟨w^,xN+1⟩\langle\hat w,x_{N+1}\rangle via t=σ(t)−σ(−t)t=\sigma(t)-\sigma(-t).

Step 2

Errors add linearly across layers because convex gradient descent is non-expansive. Stacking gives a perturbed iteration w^ℓ+1=Tη(w^ℓ)+εℓ\hat w^{\ell+1}=T_\eta(\hat w^\ell)+\varepsilon_\ell with Tη(w)=w−η∇f(w)T_\eta(w)=w-\eta\nabla f(w), and co-coercivity of a convex LfL_f-smooth ff shows that TηT_\eta never moves two points apart: ∥Tηw−Tηw′∥2≤∥w−w′∥2−η(2Lf−η)∥∇f(w)−∇f(w′)∥2≤∥w−w′∥2(η≤2/Lf).\|T_\eta w-T_\eta w'\|^2\le\|w-w'\|^2-\eta\big(\tfrac2{L_f}-\eta\big)\|\nabla f(w)-\nabla f(w')\|^2\le\|w-w'\|^2\quad(\eta\le2/L_f). Each layer passes the earlier error on without amplifying it and adds its own, so ∥w^L−wGDL∥≤Lε\|\hat w^L-w^L_{GD}\|\le L\varepsilon; the same argument around the minimizer keeps the iterates in the ball where the ReLU approximation is valid. Without convexity this fails: for GD on a two-layer network the construction needs two layers per step and the error compounds exponentially.

Step 3

Ridge, least squares and GLMs are gradient descent run for enough steps, and their risks follow by conditioning on a well-conditioned prompt. On a well-conditioned prompt the ridge objective is (α+λ)(\alpha+\lambda)-strongly convex and (β+λ)(\beta+\lambda)-smooth, so with η=1/(β+λ)\eta=1/(\beta+\lambda) gradient descent contracts like e−t/κe^{-t/\kappa} and 2κlog⁡(BxBw/2ε)2\kappa\log(B_xB_w/2\varepsilon) steps reach accuracy ε/Bx\varepsilon/B_x; the squared loss is exactly a sum of ReLUs, so the transformer adds no error. GLMs are the same argument with g(s)−yg(s)-y approximated by ReLUs, which is where the ε−2\varepsilon^{-2} heads come from. Designs with N≳dN\gtrsim d are well conditioned except with polynomially small probability, where the clipped output adds little risk, so the classical risks transfer.

Step 4

Lasso uses proximal gradient, with the MLP doing the soft threshold. Proximal gradient alternates a gradient step on the squared loss (two heads) with the ℓ1\ell_1 prox, and soft thresholding is piecewise linear, stτ(u)=σ(u−τ)−σ(−u−τ)coordinatewise,\mathrm{st}_\tau(u)=\sigma(u-\tau)-\sigma(-u-\tau)\quad\text{coordinatewise}, so a token-wise MLP of width 2d2d implements it exactly. That gives the generic βBw2/ε\beta B_w^2/\varepsilon steps without strong convexity, which fails when d>Nd\gt N. For a depth that does not grow with 1/ε1/\varepsilon, restricted strong convexity and smoothness of the Gaussian design on sparse directions make proximal gradient converge linearly to within the statistical error (as in Agarwal et al.), and the Lasso risk transfers.

Step 5

Post-ICL validation takes three layers, which score, rank and mix the candidates. Tokens carry ti=1t_i=1 for training, −1-1 for validation and 0 for the query, and the KK base algorithms run in parallel on the training split. An attention layer scores all KK on the validation tokens, with MKMK heads approximating the loss as a sum of ReLUs. An MLP ranks them: ck=∑l≠kσ(Lk−Ll)c_k=\sum_{l\ne k}\sigma(L_k-L_l) is at most γ\gamma only when Lk≤min⁡lLl+γL_k\le\min_lL_l+\gamma, and uk=σ(1−ck/γ)∈[0,1]u_k=\sigma(1-c_k/\gamma)\in[0,1] flags near-minimizers. A last attention layer mixes, f^=∑kλkfk,λk=σ(1−∑l<kul)−σ(1−∑l≤kul),\hat f=\sum_k\lambda_kf_k,\qquad \lambda_k=\sigma\Big(1-\sum_{l\lt k}u_l\Big)-\sigma\Big(1-\sum_{l\le k}u_l\Big), so λk\lambda_k is the part of a total weight of one left after the earlier flagged predictors have received theirs. The weights are nonnegative and sum to one, a soft version of the rule "take the first near-minimizer", and convexity of the risk turns this into the oracle inequality.

Step 6

Validation over KK ridge penalties is nearly Bayes-optimal for mixed noise levels, with excess risk of order N−1/3N^{-1/3}. Since BayesRiskπ≥EkBayesRiskk{\rm BayesRisk}_\pi\ge\mathbb E_k{\rm BayesRisk}_k, it suffices to compete with the oracle that knows kk: fit all KK ridges, λk=dσk2/N\lambda_k=d\sigma_k^2/N, on N−NvalN-N_{\rm val} points and pick one. The Bayes predictor averages the same ridges, but its weights P(k∣D)P(k\mid D) involve σk−(N−d)det⁡(X⊤X+dσk2I)−1/2\sigma_k^{-(N-d)}\det(X^\top X+d\sigma_k^2I)^{-1/2} and a data-dependent exponent, which attention does not compute easily. The excess comes from the lost training points, O((σk2+1)Nval/N)O((\sigma_k^2+1)N_{\rm val}/N), and from the uniform deviation of KK validation losses, O(Bw2log⁡K/Nval)O(B_w^2\sqrt{\log K/N_{\rm val}}), and balancing them sets the split: NvalN+log⁡KNvalis minimized atNval≍N2/3(log⁡K)1/3, giving (log⁡K/N)1/3.\frac{N_{\rm val}}N+\sqrt{\frac{\log K}{N_{\rm val}}}\quad\text{is minimized at}\quad N_{\rm val}\asymp N^{2/3}(\log K)^{1/3},\ \text{giving}\ (\log K/N)^{1/3}. The transformer commits to the noise level that validates best instead of carrying a posterior over it.

Step 7

Pre-ICL testing computes a statistic of the prompt first and branches on it. To tell classification from regression, average a label test over the prompt, Ψbinary(D)=1N∑iψ(yi),\Psi_{\rm binary}(D)=\frac1N\sum_i\psi(y_i), with ψ\psi a pair of tents of width ε\varepsilon at 0 and 1. Since ψ\psi is a combination of six ReLUs of yy, one 6-head attention layer computes Ψbinary\Psi_{\rm binary} exactly at every token. Another layer thresholds it into a gate in [0,1][0,1], and the network outputs the gated combination of logistic regression and least squares: for binary labels the gate is exactly 1, and for labels not concentrated near {0,1}\{0,1\} it is 0 with high probability. This is Proposition 19.

Step 8

Pretraining needs polynomially many prompts because transformers are Lipschitz in their weights. With clipping after each layer, the output on bounded inputs is Lipschitz in θ\theta with constant LBHL−1BΘLB_H^{L-1}B_\Theta, where BH,BΘB_H,B_\Theta are polynomial in BB and RR, and the norm ball has log covering number L(3MD2+2DD′)log⁡(1+2r/δ)L(3MD^2+2DD')\log(1+2r/\delta). Chaining for the bounded loss process then gives sup⁡θ∣L^icl−Licl∣≲By2(L(MD2+DD′)ι′+log⁡(1/ξ))/n;\sup_\theta|\hat L_{\rm icl}-L_{\rm icl}|\lesssim B_y^2\sqrt{(L(MD^2+DD')\iota'+\log(1/\xi))/n}; the Lipschitz constant is exponential in LL but enters only through the log, giving the extra factor LL in Theorem 20. The construction only certifies that the comparator inf⁡θLicl(θ)\inf_\theta L_{\rm icl}(\theta) is small, and the result says nothing about what SGD finds.

Step 9

Trained transformers behave as if they select an algorithm for each prompt. A 12-layer ReLU-attention encoder matches the best baseline on noiseless, noisy and sparse regression and on linear classification. Trained on a mixture of two noise levels, or of regression and classification, one model approaches the best baseline on each component, while single-task models fall short on the other task; a GPT-2 decoder does the same. This is behavioral evidence only; the trained weights are not probed for validation or testing.

Consequences and limits. "The transformer runs gradient descent" becomes quantitative: on well-conditioned convex problems the depth needed grows like the logarithm of the inverse accuracy, the number of heads sets how accurately the loss derivative is represented, polynomially many prompts suffice to find the weights, and selection by validation is nearly Bayes-optimal on a noise mixture without representing the posterior. The limits are that the constructions are existence results for ReLU attention, and the paper does not show that softmax transformers trained by SGD find them; the in-context guarantees need a well-conditioned prompt (N≳dN\gtrsim d for least squares), so the interpolation regime N<dN\lt d of the benign-overfitting papers is handled only by Lasso and ridge; the validation route's excess decays only like N−1/3N^{-1/3}; and the pretraining bound is for constrained ERM and grows with L2L^2.

Terms

ReLU attention
1N∑jσ(⟨Qhi,Khj⟩)Vhj\frac1N\sum_j\sigma(\langle Q h_i,K h_j\rangle)Vh_j in place of softmax, residual
Sum of ReLUs
∑m≤Mcmσ(am⊤[z;1])\sum_{m\le M}c_m\sigma(a_m^\top[z;1]), ∑∣cm∣≤C\sum|c_m|\le C; the heads approximate ∂sℓ\partial_s\ell in this form
ICGD layer
query carries ww, key carries (xj,yj)(x_j,y_j), value carries xjx_j: one step of w−η∇L^N(w)w-\eta\nabla\hat L_N(w)
Non-expansive GD
∥Tηw−Tηw′∥≤∥w−w′∥\|T_\eta w-T_\eta w'\|\le\|w-w'\| for convex smooth ff, η≤2/Lf\eta\le2/L_f; errors add linearly
κ\kappa
condition number (β+λ)/(α+λ)(\beta+\lambda)/(\alpha+\lambda) of the prompt; depth ≈2κlog⁡(1/ε)\approx2\kappa\log(1/\varepsilon)
Ridge as Bayes
w⋆∼N(0,I/d)w_\star\sim N(0,I/d), noise σ2\sigma^2: posterior mean is ridge with λ=dσ2/N\lambda=d\sigma^2/N
Post-ICL validation
fit KK algorithms on a train split, score on a validation split, mix near-minimizers
ck, uk, λkc_k,\ u_k,\ \lambda_k
∑lσ(Lk−Ll)\sum_l\sigma(L_k-L_l); σ(1−ck/γ)\sigma(1-c_k/\gamma); ReLU weights selecting a near-minimizer
Pre-ICL testing
compute a prompt statistic (e.g. are labels binary) in one layer, then gate between algorithms
Nval≍N2/3(log⁡K)1/3N_{\rm val}\asymp N^{2/3}(\log K)^{1/3}
balances lost training data against validation error; rate (log⁡K/N)1/3(\log K/N)^{1/3}

Quiz

  1. In the one-layer gradient step, where does the derivative ∂sℓ(⟨w,xj⟩,yj)\partial_s\ell(\langle w,x_j\rangle,y_j) get evaluated?
  2. Ridge needs at most 3 heads per layer, while a general GLM needs O~(ε−2)\tilde O(\varepsilon^{-2}). What causes the difference?
  3. Why does the paper not have the transformer compute the exact Bayes predictor for the noise mixture?
  4. What does the pretraining guarantee (Theorem 20) use the in-context constructions for?

Sources