Understanding Emergent In-Context Learning from a Kernel Regression Perspective

Chi Han, Ziqi Wang, Han Zhao, Heng Ji

TL;DR

This paper proposes that Large Language Models (LLMs) perform in-context learning (ICL) by implementing a form of kernel regression within their attention layers. By proving that Bayesian inference on prompts asymptotically converges to kernel regression and demonstrating that specific attention heads in models like GPT-J and Llama-3 act as regression engines, the authors provide a concrete bridge between high-level theory and the actual mechanics of the Transformer architecture.

What Problem Does This Paper Address?

In-context learning—the ability of an LLM to learn a task from just a few examples in a prompt without any parameter updates—is one of the most striking "emergent" properties of modern AI. However, why and how it works remains a subject of intense debate.

Existing theories generally fall into two camps:

  1. Data-centric views: These argue that LLMs are performing implicit Bayesian inference based on patterns learned during pre-training. While elegant, these theories don't explain how a fixed-depth Transformer physically computes such complex inference.
  2. Algorithm-centric views: These suggest Transformers are "simulating" optimization algorithms like Gradient Descent. However, these often rely on highly simplified, linear toy problems that don't reflect the linguistic complexity of real-world tasks.

This paper seeks to unify these views by showing that the attention mechanism is a natural fit for kernel regression, a non-parametric method that predicts an output by taking a weighted average of labels from similar training examples.

Methods

The authors approach the problem through both theoretical proof and empirical "forensics":

  • Theoretical Framework: They model natural language as a mixture of Hidden Markov Models (HMMs). They prove that as the number of demonstrations ($n$) increases, Bayesian inference on an ICL prompt converges to a kernel regression form: $$\hat{y} = \frac{\sum_i y_i K(x, x_i)}{\sum_i K(x, x_i)}$$ where $K(x, x_i)$ is a kernel measuring the semantic similarity between the test input and the examples.

  • Empirical Verification: They analyze the internal states of GPT-J 6B, Llama-2, and Llama-3 8B.

  • Output Reconstruction: To prove the model is actually "doing" kernel regression, they extracted attention weights from specific heads and plugged them into the kernel regression formula above. If the resulting prediction matches the LLM's actual output, it suggests that specific head is responsible for the ICL behavior.
  • Probing: They used Ridge regression to check if the "Key" vectors store semantic information ($T_x$) and "Value" vectors store label information ($y_i$), as their theory predicts.

Datasets

The study evaluates ICL performance across several standard NLP benchmarks:

  • SST2 & Rotten Tomatoes: Sentiment analysis.
  • Tweet Eval: Subtasks for Hate, Irony, and Offensive language detection.
  • MNLI: Natural Language Inference (detecting entailment/contradiction).
  • Synthetic HMMs: Used to verify the mathematical convergence of their theory in a controlled environment.

Key Insights and Ideas

  • The Attention-Kernel Analogy: The authors show that the Transformer attention mechanism is essentially a "kernel trick." In their view, the Query and Key vectors compute the similarity kernel $K(x, x_i)$, while the Value vectors provide the label information $y_i$.
  • Attention Spikes on Labels: A crucial finding is that during ICL, attention is not distributed randomly. Models consistently focus their attention on the specific tokens representing the labels ($y_i$) of the demonstrative examples.
Figure 2: Averaged attention map over GLUE-sst2 test set. A portion of attention on demonstrative samples is generally focused on label positions yi. This conforms to the intuition in Theorem 1 that the inference on in-context learning prompts is a weighted average over sample labels.
  • Explaining ICL "Quirks": The kernel regression perspective explains several known ICL phenomena:
  • Similarity helps: Retrieving examples similar to the test input works because it reduces bias in the kernel regression (sampling from a "local window").
  • Format sensitivity: ICL is sensitive to label formats because the labels act as the "values" being averaged; if the format changes, the "voting" space is disrupted.
  • OOD Sensitivity: Performance drops on Out-of-Distribution (OOD) inputs because the "bias" term in their convergence proof ($\epsilon_\theta$) increases when the task deviates from the pre-training distribution.

Key Results

  • High Reconstruction Accuracy: By using the attention weights from just one specific head in the middle layers (e.g., Layer 17, Head 10 in GPT-J) and applying the kernel regression formula, the authors could match the model's actual prediction with 89.2% accuracy on the SST2 task.
Figure 3: Accuracy of reconstructed outputs compared to model output (a) and ground truth (b).
  • Algorithmic Localization: The "ICL engine" isn't spread across the whole model. The kernel regression behavior emerges primarily in the middle-to-late layers (layers 16–21 for GPT-J). Earlier layers appear to be busy computing the semantic features needed for the similarity kernel.
  • Similarity Correlation: The attention values assigned to examples correlate strongly with the semantic similarity of those examples to the test input, confirming the attention mechanism acts as a similarity kernel.

Limitations and Future Work

  • Order Sensitivity: One major mystery of ICL is that the order of examples matters. Standard kernel regression is order-invariant. The authors acknowledge their current framework does not yet explain this sensitivity.
  • HMM Simplification: While HMMs are mathematically tractable, they are a simplified model of natural language. Future work could explore more complex generative models.
  • Implicit Reasoning vs. ICL: The authors note that LLMs also perform "implicit reasoning" (using their own internal knowledge) alongside ICL. Disentangling these two processes remains a challenge, especially in cases where LLMs seem robust to incorrect or random labels in the prompt.

Summary updated

Abstract

Large language models (LLMs) have initiated a paradigm shift in transfer learning. In contrast to the classic pretraining-then-finetuning procedure, in order to use LLMs for downstream prediction tasks, one only needs to provide a few demonstrations, known as in-context examples, without adding more or updating existing model parameters. This in-context learning (ICL) capability of LLMs is intriguing, and it is not yet fully understood how pretrained LLMs acquire such capabilities. In this paper, we investigate the reason why a transformer-based language model can accomplish in-context learning after pre-training on a general language corpus by proposing a kernel-regression perspective of understanding LLMs' ICL bahaviors when faced with in-context examples. More concretely, we first prove that Bayesian inference on in-context prompts can be asymptotically understood as kernel regression $\hat y = \sum_i y_i K(x, x_i)/\sum_i K(x, x_i)$ as the number of in-context demonstrations grows. Then, we empirically investigate the in-context behaviors of language models. We find that during ICL, the attention and hidden features in LLMs match the behaviors of a kernel regression. Finally, our theory provides insights into multiple phenomena observed in the ICL field: why retrieving demonstrative samples similar to test samples can help, why ICL performance is sensitive to the output formats, and why ICL accuracy benefits from selecting in-distribution and representative samples. Code and resources are publicly available at https://github.com/Glaciohound/Explain-ICL-As-Kernel-Regression.
BibTeX
@article{han2025understanding,
  author = {Chi Han and Ziqi Wang and Han Zhao and Heng Ji},
  title = {{Understanding Emergent In-Context Learning from a Kernel Regression Perspective}},
  journal = {Accepted by TMLR},
  year = {2025},
  url = {https://openreview.net/forum?id=6rD50Q6yYz},
}
Figure