Transformers learn in-context by gradient descent

Johannes von Oswald, Eyvind Niklasson, Ettore Randazzo, João Sacramento, Alexander Mordvintsev, Andrey Zhmoginov, Max Vladymyrov

Abstract

At present, the mechanisms of in-context learning in Transformers are not well understood and remain mostly an intuition. In this paper, we suggest that training Transformers on auto-regressive objectives is closely related to gradient-based meta-learning formulations. We start by providing a simple weight construction that shows the equivalence of data transformations induced by 1) a single linear self-attention layer and by 2) gradient-descent (GD) on a regression loss. Motivated by that construction, we show empirically that when training self-attention-only Transformers on simple regression tasks either the models learned by GD and Transformers show great similarity or, remarkably, the weights found by optimization match the construction. Thus we show how trained Transformers become mesa-optimizers i.e. learn models by gradient descent in their forward pass. This allows us, at least in the domain of regression problems, to mechanistically understand the inner workings of in-context learning in optimized Transformers. Building on this insight, we furthermore identify how Transformers surpass the performance of plain gradient descent by learning an iterative curvature correction and learn linear models on deep data representations to solve non-linear regression tasks. Finally, we discuss intriguing parallels to a mechanism identified to be crucial for in-context learning termed induction-head (Olsson et al., 2022) and show how it could be understood as a specific case of in-context learning by gradient descent learning within Transformers.

Introduction

Large Language Models (LLMs) exhibit a remarkable ability called In-Context Learning (ICL): they can learn to solve a new task just by looking at a few examples in a prompt, without any changes to their permanent weights. While we know that it works, the mechanistic "how" has remained largely a mystery. This paper addresses whether the Transformer is actually running an optimization algorithm like Gradient Descent (GD) inside its forward pass. By bridging the gap between the architecture of self-attention and the math of gradient-based optimization, the authors provide a mechanistic understanding of how these models adapt on the fly.

Methods: The Transformer as a Mesa-Optimizer

The researchers take a constructive approach combined with empirical validation to demonstrate that Transformers can implement optimization algorithms internally.

Weight Construction

They mathematically derive a specific set of weights for a Linear Self-Attention (LSA) layer that makes its output identical to one step of Gradient Descent on a least-squares regression task. This reveals that the self-attention mechanism—which computes weighted sums of values based on key-query similarities—is mathematically equivalent to the update term in a gradient descent step.

Conceptual equivalence and empirical validation of Transformers as gradient descent optimizers.

Iterative Refinement and Non-linear Extensions

The hypothesis is extended to multi-layer Transformers, showing how successive layers can perform "curvature correction" (termed GD++) to converge faster than standard gradient descent. By adding Multi-Layer Perceptrons (MLPs), the architecture can perform GD on deep representations, effectively solving non-linear problems like sine-wave regression.

Key Results

The study focuses on controlled, synthetic environments like linear regression and non-linear sine waves to ensure mechanistic clarity.

  • Perfect Alignment: When a single-layer LSA Transformer is trained on regression, its learned weights show almost perfect alignment with the theoretical GD construction.
  • Algorithmic Equivalence: In out-of-distribution (OOD) tests, the Transformer's error patterns closely match those of Gradient Descent, suggesting they are indeed using the same underlying logic.
  • Phase Transitions: The authors observed "grokking"-like behavior during training. As shown in the training dynamics, the model suddenly transitions from poor performance to perfectly matching the GD algorithm.
Training dynamics showing a phase transition where the Transformer's behavior suddenly aligns with gradient descent.

Discussion

While groundbreaking, the paper focuses on regression tasks with squared error losses. Extending this to the cross-entropy loss used in language modeling is a natural next step. Additionally, a major open question is how these "mesa-optimizers" scale up to billion-parameter models and whether more complex optimization algorithms (like Adam or second-order methods) emerge in larger architectures. The authors suggest that we might be able to design better architectures by explicitly baking in these optimization-friendly structures.

Code to reproduce the experiments can be found at https://github.com/google-research/self-organising-systems/tree/master/transformers_learn_icl_by_gd.

Summary updated

BibTeX
@inproceedings{oswald2023transformers,
  author = {Johannes von Oswald and Eyvind Niklasson and Ettore Randazzo and João Sacramento and Alexander Mordvintsev and Andrey Zhmoginov and Max Vladymyrov},
  title = {{Transformers learn in-context by gradient descent}},
  booktitle = {International Conference on Machine Learning},
  year = {2023},
  url = {https://openreview.net/forum?id=tHvXrFQma5},
}
Figure