Skip to main content
ExplainerIn-Context LearningMechanism Explainer· 4 min read· in Artificial Intelligence

The Mesa-Optimization Engine: How Transformers Simulate Gradient Descent to Learn In-Context

Researchers have discovered that large language models perform in-context learning by running a hidden optimization algorithm during their forward pass. By mathematically simulating gradient descent within their attention heads, transformers can build and update implicit models on the fly without altering their permanent weights.

By Sofia Matos

Theoretical Mechanists 40%Empirical Skeptics 35%AI Safety Researchers 25%
Theoretical Mechanists
Argue that in-context learning is mathematically equivalent to standard optimization algorithms.
Empirical Skeptics
Argue that real-world language models deviate significantly from pure gradient descent due to order sensitivity and layer causality.
AI Safety Researchers
Focus on the alignment risks of models running hidden, internal optimization loops with potentially misaligned objectives.

A modern large language model can learn to translate a new fictional language or format complex code from just 3 examples in a prompt, a feat that would traditionally require updating 70 billion to 1 trillion parameters over 100,000 training steps. This capability, known as in-context learning, allows a frozen model to adapt to novel tasks instantly. For years, the mechanism behind this adaptation was treated as an emergent mystery—a byproduct of scaling up data and compute. But recent theoretical work has revealed a concrete mathematical engine driving the phenomenon: the transformer architecture is secretly running its own internal optimization algorithm.[7]

The traditional way to teach a neural network is through gradient descent. In this standard process, an external algorithm measures the model's error on a dataset and updates its permanent weights to minimize that error. This requires a backward pass through the network, which is computationally expensive and permanently alters the model. In-context learning, by contrast, happens entirely in the forward pass. The model's weights remain locked, yet its outputs improve as if it had been explicitly trained on the prompt's examples.[7]

Researchers from Google, MIT, and Microsoft have independently demonstrated that these two processes are mathematically linked. According to a foundational December 2022 paper by Johannes von Oswald and colleagues at ETH Zürich and Google Research, a transformer's self-attention layer can be constructed to exactly simulate a step of gradient descent. Instead of updating the model's actual weights, the attention heads update an 'implicit model' stored temporarily within the network's activations.[1]

How the self-attention mechanism mirrors the mathematical steps of gradient descent.

This phenomenon is known as mesa-optimization—a scenario where a system trained by an external optimizer learns to become an optimizer itself. As lead author Johannes von Oswald, a researcher at ETH Zürich, wrote in the foundational 2022 study, 'trained Transformers become mesa-optimizers i.e. learn models by gradient descent in their forward pass.' The base optimizer, such as stochastic gradient descent, searches for weights that minimize training loss. The resulting weights happen to encode a forward pass that runs an internal search loop. The transformer is not just retrieving memorized facts; it is actively computing a learning algorithm at runtime.[1][2][7]

This phenomenon is known as mesa-optimization—a scenario where a system trained by an external optimizer learns to become an optimizer itself.

The mechanics of this simulation rely on the core operations of the self-attention mechanism: queries, keys, and values. When a prompt contains several examples followed by a new test query, the attention mechanism computes the similarity between the new query and the previous examples, which act as the keys. Ekin Akyürek and researchers at MIT showed that by multiplying these similarities by the example outputs, or values, the attention head effectively calculates a gradient step. The context examples act as a temporary training dataset, and the attention matrix applies the resulting gradient update to the test query's representation.[3]

This internal optimization is not limited to a single step. While a single attention layer can simulate 1 iteration of gradient descent, deeper models can chain these operations together. An October 2024 study by Bo Chen and colleagues demonstrated that looped transformers can implement multi-step gradient descent, refining the implicit model's accuracy with each successive layer. Other researchers have even found evidence that transformers can approximate higher-order optimization methods, such as Iterative Newton's Method, allowing them to converge on solutions exponentially faster than standard gradient descent.[6]

Mesa-optimization occurs when an outer training process produces a model that runs its own inner learning algorithm.

However, the hypothesis that real-world language models perfectly mirror gradient descent remains contested. The mathematical proofs rely heavily on stylized settings, such as linear regression tasks with zero-mean Gaussian priors. When researchers test these theories on models pre-trained on natural language, the equivalence begins to fray. A November 2023 study by Gilad Deutch and researchers at Bar-Ilan University highlighted a discrepancy called 'Layer Causality.' In standard gradient descent, updates depend on errors calculated across all layers. In in-context learning, the information influencing a hidden state comes only from earlier layers, breaking the exact parallel.[4]

Furthermore, empirical tests by Lingfeng Shen at Johns Hopkins University in October 2023 showed that in-context learning and gradient descent exhibit different sensitivities to the order of examples. If a transformer were running pure gradient descent, the order of the prompt examples should not drastically alter the final implicit model. Yet, real-world models are highly sensitive to prompt ordering, suggesting that while the mesa-optimization framework is a powerful analogy, the actual algorithm learned by billion-parameter models is something distinct and uniquely adapted to sequence modeling.[5]

Despite these caveats, the discovery that transformers can encode learning algorithms within their weights fundamentally shifts how researchers view artificial intelligence capabilities. It suggests that scaling up models does not just increase their capacity to memorize data, but expands their ability to run complex, internal software. The next frontier in mechanistic interpretability is isolating these mesa-optimizers in the wild, determining exactly what objective they are optimizing, and ensuring that their internal goals align with the external tasks they are given.[7]

Limits of the evidence

  • Whether billion-parameter models trained on natural language use the exact gradient descent math proven in stylized linear regression tasks.
  • How to reliably extract and read the 'implicit models' stored temporarily in a transformer's activations.
  • Whether these internal mesa-optimizers can develop deceptive goals that bypass standard AI safety guardrails.

Significance

If in-context learning is driven by a hidden, internal optimization process, it means AI models are not just retrieving patterns, but actively learning new algorithms at runtime. Understanding this mechanism is critical for controlling model behavior, designing more efficient architectures, and anticipating how future systems might optimize for unintended goals.

Sources

Source coverage

7 outlets

3 viewpoints surfaced

Theoretical Mechanists 40%Empirical Skeptics 35%AI Safety Researchers 25%
  1. [1]arXivEmpirical Skeptics

    Transformers learn in-context by gradient descent

    Read on arXiv
  2. [2]arXivEmpirical Skeptics

    Why Can GPT Learn In-Context? Language Models Secretly Perform Gradient Descent as Meta-Optimizers

    Read on arXiv
  3. [3]arXivEmpirical Skeptics

    What learning algorithm is in-context learning? Investigations with linear models

    Read on arXiv
  4. [4]arXivEmpirical Skeptics

    In-context Learning and Gradient Descent Revisited

    Read on arXiv
  5. [5]arXivEmpirical Skeptics

    Do pretrained Transformers Learn In-Context by Gradient Descent?

    Read on arXiv
  6. [6]arXivEmpirical Skeptics

    Bypassing the Exponential Dependency: Looped Transformers Efficiently Learn In-context by Multi-step Gradient Descent

    Read on arXiv
  7. [7]Factlen Editorial TeamAI Safety Researchers

    Synthesis by Factlen editorial team

    Read on Factlen Editorial Team

Comments

Stay informed

Every angle. Every day.

Get Artificial Intelligence stories with full source coverage and perspective breakdowns delivered to your inbox.