Transformers Learn In-Context by Gradient Descent
Citation. Johannes von Oswald (ETH Zürich and Google Research), Eyvind Niklasson, Ettore Randazzo, João Sacramento (ETH Zürich), Alexander Mordvintsev, Andrey Zhmoginov and Max Vladymyrov (Google Research). "Transformers Learn In-Context by Gradient Descent". Proceedings of the 40th International Conference on Machine Learning (ICML 2023), PMLR 202. arXiv 2212.07677 [cs.LG]: v1 15 December 2022, v2 31 May 2023. We read v2. Paper. Notebooks for the main experiments are at google-research/self-organising-systems. The tasks are synthetic, so there is no dataset to link. A Swiss National Science Foundation Ambizione grant (PZ00P3 186027) and an ETH Research Grant (ETH-23 21-1) supported Sacramento. The paper gives no statement about tools or help from an LLM. The ICML year agrees with the v2 date.
Status. Planned. #4782 would use it in its synthesis on weight-space programming and fast weights. The paper is the clearest case where a reading of weights alone names the algorithm that a trained layer runs. It also shows the conditions that this reading needs, and the registry's models meet none of them. The page proposes one small follow-up issue.
Read. We read the arXiv v2 PDF on 2026-11-19, as text that pdftotext took from it. We have the source's own text for the abstract, §1 to §5, the acknowledgements and the references. We also have Appendices A.1 to A.12, which hold the constructions, the softmax and LayerNorm results, phase transitions and the hyperparameters. We also read the arXiv abstract page for the version history. We did not see the 16 figures as images. Most results are only in the figures, so this page gives the text's own words for them and no number read off a plot. Some equations came out of the extraction with their layout broken. We read them against the text around them. A model (Claude Opus 5.5) did the reading itself, with no subagent.
Summary
Claim. One linear self-attention layer can do the same update as one step of gradient descent on a squared-error regression loss over the in-context data. Self-attention-only transformers trained on such regression tasks find this construction, or a close variant. So the trained model learns by gradient descent in its forward pass, a "mesa-optimizer". The authors hypothesise that in-context learning in language models comes from similar mechanisms.
Method.
- Linear self-attention (LSA). A standard self-attention layer with the softmax removed, following Schlag et al. (2021). Each token gets the sum over heads of
P_h V_h K_hᵀ q_{h,j}. The paper leaves out bias terms. - Proposition 1. The tokens are
e_j = (x_j, y_j), one per training pair, and a query token holds the test input. Appendix A.1 gives block weights:W_K = W_Qselect x,W_Vholds the initial modelW_0and−I_y, andP = (η/N)I. One layer then moves each targety_jtoy_j − ΔW x_j, with ΔW one gradient step. Only the productsP W_VandW_Kᵀ W_Qmatter, and any scalarscan rescale one against the other. - GD++. Several layers can also transform the inputs,
x_j ← (I − γXXᵀ)x_j. The paper calls gradient descent with this extra step GD++, and treats it as a curvature term (Appendix A.10). - Proposition 2. An MLP before the attention layer makes the step a gradient step on a linear model over the MLP's features. This is kernel regression with kernel
m(x)ᵀm(y). - Proposition 3. Take one token for each x and one for each y, plus positional codes. Then one attention layer can copy the next token's target into the current token. That builds the tokens that Proposition 1 needs.
- Tasks. Linear regression with a teacher
W_τ ~ N(0, I), inputs fromU(−1, 1), no noise, and N = n_I = 10, n_O = 1 in most runs. Sine-wave regression for Proposition 2. The loss is on the last token only, and each training step draws new tasks. - Baselines and metrics. Gradient descent from
W_0 = 0with η, and γ for GD++, tuned on 10⁴ tasks. On 10⁴ validation tasks the paper compares the predictions (L2 distance), the sensitivities ∂ŷ/∂x (cosine and L2) and the loss. It also interpolates between the trained weights and the construction after one scale adjustment. Last, it tests out-of-distribution input ranges and teacher scales. - Settings (Appendix A.12). Adam at 0.001 for depth K < 3 and 0.0005 otherwise, batch 2048 and gradient clipping at norm 10. The initialisation is a truncated normal with std 0.002/K. The authors clip token values to [−10, 10], and the positional codes have size 20.
Findings, as the source reports them.
| Setting | Result |
|---|---|
| One trained LSA layer against one GD step (§3, Figure 2) | "excellent agreement between the two models over a wide range of hyperparameters". Figure 2 shows the mean and std, or single runs, of 5 seeds |
| The same, in weight space (§3, Appendix A.4, Figure 9) | After one scalar adjustment, the trained weights show the construction. The interpolated weights give "identical loss" |
| The trained layer, applied again and again (Appendix A.6) | Both GD and the layer diverge quickly. With a damping λ = 0.75, both lower the loss steadily over 50 steps |
| Recurrent two-layer LSA (§3, Figure 3a) | It beats plain GD, and "realigns perfectly with GD++" |
| Five-layer LSA, no weight tying (§3, Figure 3b) | "almost perfect alignment" with GD++, which has "10 additional parameters". Interpolation fails with the simple scale adjustment, and works "only for some seeds" (Appendix A.3) |
| Sine-wave regression, MLP plus LSA (§3, Figure 4, Appendix A.7) | Amplitude from U(0.1, 5), phase from U(0, π), N = 10, a 40-dimensional embedding and a 160-unit GELU MLP. The text reports "strong alignment" with a meta-learned MLP plus one GD step |
| Two layers on alternating x and y tokens (§4, Figure 5) | The loss matches one GD step, "not two", and training takes "an order of magnitude longer". The first layer becomes sensitive to token j + 1 just before the loss drops. Training worked only with softmax in the first layer |
| One softmax head (Appendix A.9, Figure 12) | It cannot match GD. Two heads "significantly" reduce the gap, and their off-diagonal QK terms cancel in the sum (Figure 11) |
| LayerNorm before attention (Appendix A.9, Figure 14) | Worse loss than GD and lower alignment. "Including more heads does not help substantially" |
| Training seeds (Appendix A.11, Figure 15) | With one head, some of 10 seeds show long phases of almost no progress before a sudden drop. Two heads remove this |
| A fixed set of 8,192 tasks, with an MLP (Appendix A.11) | Grokking-like curves, with a final test loss near the GD loss of 0.2 |
| A fixed set of 128 tasks (Appendix A.12, Figure 16) | The trained layer still aligns "remarkable well" with the construction |
Where the claims go beyond the evidence
- The title is wider than the experiments. Every result is on small self-attention-only models, regression tasks and in most runs 10-dimensional inputs. The discussion says this: "our findings are restricted to small Transformers and simple regression problems". The abstract's mechanistic claim keeps the words "at least in the domain of regression problems". The title does not.
- The setup is not language modelling. The loss is on the last token only, the teacher has no noise, and each task is new. The authors say that this "stands in contrast to usual autoregressive training". The Proposition 3 construction also copies from token j + 1 to token j, and Figure 5 shows that dependence. A causal language model cannot attend to a later token. So the step from this setup to induction heads in language models is an argument, not a test.
- The clean weight match needs linear attention. With softmax, one head cannot match GD, and two heads match it less well than linear attention. LayerNorm lowers both loss and alignment. The "standard Transformer" result in §3 rests on "slight architectural modifications", in the authors' words. The paper then hopes that the cost is "negligible" in deep and wide models, with no test.
- The authors check the weight match by eye and by interpolation. Figure 9 shows the products after one scalar adjustment, and the text says "perfect resemblance". The paper gives no distance in weight space, and no null from random or untrained weights. For five non-recurrent layers, the interpolation fails except for some seeds.
- Few numbers and few seeds. The main results are curves for 5 seeds, with no intervals in the text and no test of the alignment against a baseline. The phase transitions in Appendix A.11 depend on the seed, and §4 says that training speed varies "highly" across seeds.
- The copy mechanism is a two-layer toy. §4 calls copying "the second crucial mechanism for in-context learning in Transformers". The evidence is one two-layer model whose loss reaches one GD step, not two, and needs softmax in its first layer.
The authors state several limits themselves. These are the restriction to small models and regression, the missing noisy and logistic cases, and the failed interpolation for deep models. They also say that their mechanism may be "one of many possible methods giving rise to in-context learning".
Use in this repo
- The paper is a case where weights alone name the algorithm. After one scalar adjustment,
W_Kᵀ W_QandP W_Vof a trained layer show the gradient-step construction. That is a check with no forward pass. It works because three things hold. The construction is known in advance, the layer is linear, and the only symmetry left is one scalar. The registry's four models (pyproject.toml) have softmax attention, LayerNorm or RMSNorm, MLPs and causal masks. No explanation in the registry comes with a construction to compare against. - Even here, forward passes back the weight reading. The paper's evidence for the match is the predictions, the sensitivities and the loss on 10⁴ validation tasks. Figure 9 only adds to that. For deeper models the weight reading fails, while the forward-pass alignment stays high. So the paper supports a weight reading as a cheap first check, not as a substitute for the review's probes.
- This agrees with what the repo measured.
docs/analyses/weight-kurtosis.mdreads ROTATE's vocabulary kurtosis from weights alone (#3446). On 518 test poles, its AUC for VERIFIED is 0.51 (0.45–0.57) on the output side and 0.54 (0.48–0.60) on the input side. Indocs/analyses/ground-truth-calibration.md, plants written as input weights passed for 7 of 12 rules, and for none that needs context. Both readings had no known construction to compare against, unlike the paper's. - The paper's argument, like Ba et al.'s, puts the in-context rule in the activations. The learned ΔW never exists as a weight. It lives in the tokens during one forward pass. That is the same limit as
docs/literature/fast-weights-recent-past.mdanddocs/literature/linear-attention-transformers-are-rnns.mdgive. A unit whose explanation depends on context can't be checked from static weights. #5144 counts how many VERIFIED explanations are of that kind, and this paper adds no new number to it. - The repo already reads head weights, without a construction.
openinterpretability/core/wiring.pyranks a head's connections through its OV circuit and its Q, K and V reads, as virtual weights. The page says that these rank units but have no absolute scale. #5062 (an OV vocabulary lens) and #3457 (head type from weights) would add more readings of this kind. The paper's Figure 9 method is the step after those: compare the products with an explicit construction. The repo knows a construction for one kind of head. A previous-token head's QK circuit on positions should peak at offset −1. The registry measures that pattern withpattern_scores(openinterpretability/harness/heads.py), from forward passes on repeated random tokens. - The copy step is close to the registry's head types. Proposition 3 and Figure 5 describe a first layer that merges one token with its neighbour. In a causal model the neighbour must be the earlier token, which is a previous-token head. The paper ties this to induction heads, and
docs/literature/induction-heads-in-context-learning.mdcovers the registry's induction scores. The paper's gradient-descent view gives no new probe for those heads. Its tasks have no tokens from a vocabulary. - Weight-space programming (#3381, #4471). Proposition 1 is weight-space programming by hand: the authors write weights that run a known algorithm, and training then finds them. The repo's own written weights are the ground-truth plants (
scripts/ground_truth.py). They write one neuron's input weights, and no attention head. The paper's constructions would be a head plant with a known answer, but its LSA layer is not in any registry model. - MLP neurons. In Proposition 2 the MLP gives the features of a kernel. The paper does not read any of its 160 neurons on their own. Nothing in it bears on a pole's verdict, and it has no probes or null for single units.
- Proposed follow-up. GPT-2 has learned absolute positions. On GPT-2, read each head's QK circuit on the position embeddings from weights alone. Then compare the share at offset −1 with the head's measured previous-token score. That tests, on registry heads, whether a known construction lets weights stand in for a forward-pass pattern. Area: research questions, priority: low.
- Question for the maintainer. Could a weight match to a known construction ever count toward a head's verdict, with no probes? That would change the decision rule and need a
PROTOCOL_VERSIONbump (docs/PROTOCOL.md§6). We record it as a question only.