AI State of the Art
Fundamentals/LLM: Understanding Large Language Models/23 min
Section 58

In-Context Learning: How Does It Work?

Listen as a podcast →

Learning Without Modifying the Brain

Imagine someone who doesn't speak Japanese. You show them five Japanese sentences with their English translations. And against all odds, they translate the sixth, without ever having studied Japanese, without lessons, without a dictionary. How? Because this person is an experienced polyglot who has already learned twenty languages: they did not learn Japanese from five examples, they recognized the translation procedure and drew on what they already knew.

This is exactly what large language models (LLMs) do with in-context learning (ICL). You show them a few examples in the prompt, they spot the regularity and apply it to a new case.

The remarkable part is this, and it is worth weighing the word "learning" in the name: it happens without any modification to the model's weights. No backpropagation (the mechanism that walks back through the network to correct weights), no gradients, no training. The model is bit-for-bit identical before and after. Only its context has changed. So this is not learning in the usual sense of the word, and much of the debate on this page is about how to name what is actually going on.

ICL prompt example:

French -> English chat -> cat maison -> house voiture -> ???

The model responds "car." It has "learned" the translation task from three examples, solely during inference.

The Discovery That Changed Everything: GPT-3 in 2020

Before 2020, adapting an NLP (Natural Language Processing) model to a new task always meant the same thing: fine-tuning it, that is, modifying its weights on a specialized dataset. It was slow, expensive, and you ended up with a different model per task. Sentiment classification? One model. Translation? Another. Summarization? A third.

In 2020, the GPT-3 paper by Brown et al. changed that: with a large enough model (175 billion parameters), fine-tuning becomes unnecessary for many tasks. GPT-3 handles dozens of them competitively, simply by being given a few examples in the prompt.

Language Models are Few-Shot Learners (Brown et al., 2020)

The authors distinguish three regimes. "Shot" here means "example supplied in the prompt":

  • Zero-shot: only a natural-language instruction, no examples, "Translate this sentence into French: ..."
  • One-shot: a single worked example, followed by the new input
  • Few-shot: several examples showing the expected regularity. The authors state their own practice: they set that number "in the range of 10 to 100, as this is how many examples can fit in the model's context window"
Figure from the GPT-3 paper titled the three settings we explore for in-context learning. In zero-shot, the prompt contains only the task description Translate English to French followed by the word cheese. In one-shot, a single example is added, sea otter gives loutre de mer. In few-shot, several examples are stacked before the word to translate. In all three cases, no gradient updates are performed.
The three regimes as the GPT-3 authors define them, on a single translation task. You go from zero to one to several examples in the prompt, and nothing else changes: the repeated no gradient updates line is there to remind you that the model's weights are never touched.Source : GPT-3 paper, Brown et al., 2020 (figure 2.1), via InfoQ
The Paradigm Shift

Before ICL: one specialized model per task, several days of fine-tuning per use case, and machine learning (ML) skills required throughout. After ICL: a single generalist model, five examples in the prompt, an immediate result, available to any developer. The barrier to entry went from several days of specialist work to a few minutes of writing. That is what made LLMs usable by the general public.

How Does It Work? Three Competing Theories

This is one of the most fascinating mysteries of modern deep learning: why does ICL work? The weights don't change, yet the model adapts to a new task. Several theories coexist, each illuminating a different aspect of the phenomenon.

Theory 1: Implicit Gradient Descent

The boldest explanation. Akyürek et al. (2022) and von Oswald et al. (2023) showed mathematically that a Transformer's attention layers can carry out, within a single forward pass (the computation that runs from input to output, with no weight modification whatsoever), something formally equivalent to a gradient descent.

Here it is essential to keep straight what is learned and what is computed. The model's weights do not move, they are frozen parameters. What plays the role of "weights" in this internal gradient descent are activations: values computed on the fly from the current text, which vanish as soon as the answer is produced. The Transformer simulates a training run inside its working memory, without ever touching its long-term memory.

The theory is elegant and precise, but it has mainly been verified on heavily simplified Transformers (one or two layers) and on linear regression tasks. Extending it to real LLMs remains an open research question.

Theory 2: Bayesian Task Selection

Another perspective: the pre-trained model has absorbed hundreds of thousands of different tasks during pre-training. The examples in the prompt simply serve to "select" which of these known tasks applies here.

ICL as Recognition, Not Learning

On this theory, the model learns nothing from the examples. It recognizes that they belong to a procedure already encountered during pre-training, and replays it. That is retrieval from memory, not acquisition.

What makes this reading useful is that it yields a testable prediction: if it really is recognition, then ICL should work very well on familiar tasks and fail on genuinely novel ones. That is what we observe, see the section on limits below.

Theory 3: Skill Composition

The most pragmatic perspective. Large models acquired elementary skills during pre-training: grammar, translation, arithmetic, formatting, logic. The examples in the prompt indicate how to combine those building blocks for the task at hand. Less learning than bespoke assembly, like a cook who has every ingredient and is handed the recipe.

Induction Heads: An Identified Mechanism

Induction heads are the most concrete result on the "how" of ICL. Olsson et al. (2022) identified pairs of attention heads that cooperate to perform a simple operation:

if the model sees the sequence [A][B] ... [A] in its context, it predicts [B] after the second [A].

In plain terms: "if I have already seen B follow A somewhere in this text, then when A comes back, I predict B." It is a conditional copy, and it is exactly the operation ICL requires. When you write "chat -> cat, maison -> house, voiture -> ?", the model has seen the "French word, arrow, English word" procedure three times and replays it on the fourth.

In-context Learning and Induction Heads (Olsson et al., 2022)
A Phase Transition During Training

Induction heads do not exist in an untrained model. The authors observe that they form during a phase transition in the course of training: at one specific moment the loss curve shows a visible bump, the induction heads appear, and in-context learning switches on almost at once.

This is a striking result because it ties the debate on the emergent abilities page to a mechanical observation: here we do not merely record a jump in scores, we watch the circuit that produces it come into being.

What Influences ICL Performance

More Examples, but with Diminishing Returns

In general, more examples give better results, but each additional example is worth less than the last. The GPT-3 paper's curves show that shape: most of the gain is captured by the first few examples, then the curve flattens. Exactly where it flattens depends on the task, and we give no numeric threshold, there is no universal one.

Plot of accuracy in percent against the number of examples in context, for three model sizes: 1.3 billion, 13 billion and 175 billion parameters. The zero-shot, one-shot and few-shot regions are annotated at the top. The 175 billion curve rises from 8 to about 65 percent then flattens, the 13 billion curve climbs slowly to 25 percent, and the 1.3 billion curve stays below 5 percent. Two line styles distinguish a natural language prompt from no prompt.
The blue curve (175 billion parameters) shows diminishing returns exactly as described: most of the gain is captured by the very first examples, then the curve flattens out. Note too that a natural language task description (solid line) is by itself worth several examples compared with no instruction at all (dashed line).Source : GPT-3 paper, Brown et al., 2020 (figure 1.2), via Academia.edu

Example Order: A Detail That Matters

Surprising but documented: the order alone in which you present the examples changes the results. Lu et al. (2021) sum the effect up in a sentence worth more than a number: depending on the ordering, the same set of examples can take you from near state-of-the-art performance to near random. And the good orderings are hard to predict in advance.

Quality and Diversity

Clear, varied examples representative of the task's different cases beat redundant ones. Diversity helps the model generalize instead of copying.

Model Size

ICL is a capability that comes with scale: the GPT-3 paper's curves show that on small models the gap between zero examples and several examples is nearly nil (giving examples does nothing) and that this gap widens as the model grows. We give no numeric threshold: it depends on the task and the models involved, and it falls with each generation.

Plot of aggregate performance across a set of benchmarks against model size, from 0.1 to 175 billion parameters. Three curves: few-shot, one-shot and zero-shot. All three rise with model size, but the gap between few-shot and zero-shot widens: it is almost nil at 0.1 billion and reaches roughly fifteen points at 175 billion.
This plot is why ICL is called an emergent capability. On the left, for small models, giving examples barely helps: the three curves sit on top of each other. As the model grows, the gap between few-shot and zero-shot widens, the ability to exploit the examples in the prompt is what appears with scale.Source : GPT-3 paper, Brown et al., 2020 (figure 1.3), via Academia.edu

Limitations to Know

The context window: the number of examples is capped by the context window, that is, by how much text the model can read at once. On recent models it runs to hundreds of thousands of tokens. That sounds like plenty, but rich examples (with their context and explanation) eat the space fast, and the model's attention thins out before the limit is even reached.

Out-of-distribution tasks, tasks whose nature differs from what was in the training data: ICL works well on things that resemble the already-seen. For a genuinely novel task, an invented programming language, a radically new taxonomy, non-standard logic, results stay poor. This is exactly what theory 2 predicts: the model cannot acquire something new from ten examples, it can only reconfigure what it already has.

ICL Does Not Replace Fine-tuning

For a task requiring deep, reliable adaptation (thousands of examples, a highly specialized domain, strict format constraints) fine-tuning remains superior. ICL is excellent for fast prototyping, imposing a format, or nudging a simple behaviour. For robust production on a specific task, fine-tuning keeps the edge.

Sensitivity to surface cues: the model can latch onto an incidental detail rather than the logic of the task. If all your "positive" examples start with "I," it may associate "I" with positive instead of reading the sentence's content. This failure mode is insidious, because it stays invisible as long as your test cases look like your examples.

In-context Learning in Practice

ICL is the foundation of prompt engineering. Understanding it tells you why certain techniques work: giving examples shows the procedure, showing the output format guides the structure, varying the examples improves generalization.

In practice:

  • start with three to five varied examples covering the different cases of your task;
  • show the exact output format in your examples, the model will reproduce it faithfully, defects included;
  • if results fall short, add examples before considering fine-tuning;
  • order matters: put the most representative examples at the start and the end. Models exploit the beginning and end of a long context better than its middle, an effect documented under the name "lost in the middle."

This is also why LLMs are so flexible: one model is "programmed" for hundreds of tasks by changing the prompt alone. The following pages cover the more advanced techniques, chain-of-thought and structured output.

Check your understanding0 / 4

1. In the implicit gradient descent theory, what plays the role of the adjusted weights?

2. What verifiable prediction does the Bayesian task-selection theory (ICL as recognition) make?

3. What do the induction heads identified by Olsson et al. do?

4. What effect can the mere order of the prompt's examples have?