Dev.to AI 🤖 Ai 👁 0 📖 14 min read

How does a model learn from examples it was never trained on?

Originally published on Medium. Give a language model a few worked examples inside the prompt, and it will do a new task it was never explicitly trained to do. Show it three English sentences translated into French, the

Originally published on Medium.

Give a language model a few worked examples inside the prompt, and it will do a new task it was never explicitly trained to do. Show it three English sentences translated into French, then an English sentence with no translation, and it produces the French. Show it a few movie reviews labeled positive or negative, then an unlabeled one, and it classifies it. No weights change. No gradient step runs. The model simply reads the examples and adapts, on the spot, in a single forward pass.

This is in-context learning, and it is the capability that turned language models from text predictors into general-purpose tools. It is also genuinely strange. Learning, in machine learning, has always meant updating parameters. Here there are no updates, and yet the behavior changes as if the model had learned something. This post explains what in-context learning is mechanically, the three main explanations for how it works, what the evidence says each explanation gets wrong, and why the question matters beyond a party trick.

What in-context learning actually is

A language model is a function that takes a sequence of tokens and predicts the next one. In-context learning exploits that function without touching it. You put the task description and a handful of examples into the prompt, add the new input, and let the model complete the sequence. The model was trained to predict text, and the prompt is arranged so that the most likely continuation is the correct answer to your task.

A concrete example makes the mechanics clear. Suppose you want sentiment labels. Your prompt might look like this:

Review: "The film was a joy from start to finish." Sentiment: Positive
Review: "Two hours I will never get back." Sentiment: Negative
Review: "The acting carried an otherwise thin plot." Sentiment:

The model has to predict the next token. Given the pattern, "Positive" is the most likely continuation. Nothing about the model changed between the first example and the last line. The examples are just text in the context window, and the model conditions on all of it when it predicts.

The zero-shot version works the same way with no examples at all, just an instruction. The few-shot version, with examples, is usually more reliable, because the examples do two jobs at once. They specify the task, which the model may or may not infer from an instruction alone, and they specify the format, so the answer comes back in the shape you want.

This is worth stating plainly, because it is easy to blur. In-context learning is not fine-tuning. Fine-tuning changes the weights and the change persists. In-context learning changes nothing permanently. Close the session and the model forgets the examples entirely. The "learning" is entirely in the activations, the pattern of numbers flowing through the network during that one forward pass, and it vanishes the moment the pass is over.

Why it was a surprise

Before GPT-3, the standard way to adapt a model to a task was to train it on that task. BERT-era practice was pretrain once, then fine-tune a copy per task, on labeled data, with gradient descent. GPT-3, described by Brown and colleagues in 2020, showed that a large enough model could skip the fine-tuning step entirely. Give it examples in the prompt and it performed tasks it had never been trained on, sometimes competitively with fine-tuned models.

The surprise was not just that it worked. It was that it worked without any mechanism designed for it. GPT-3 was trained on one objective, predict the next token on internet text. Nobody added a learning algorithm to it. Nobody trained it to learn from examples in context. The ability appeared as a side effect of scale and of the data, which is full of situations where a pattern repeats and then a new instance of the pattern appears. A list of questions and answers, a document with examples followed by a test case, a conversation where a speaker's style is established and then continues: the internet is full of sequences where the right move is to infer the pattern from the preceding text and continue it. A model trained to predict such text gets good at exactly that skill, and in-context learning is what that skill looks like when you point it at a task.

Scale mattered, and that is part of the story. Small models show weak or no in-context learning. As models grew, the ability strengthened, and at some size it went from a curiosity to a reliable interface. Researchers still argue about whether this counts as an emergent ability or a smooth improvement that only looks sudden because of how it is measured, but the practical fact is not disputed: below a certain scale, few-shot prompting barely works, and above it, it is the default way people use these models.

Explanation one: the model copies patterns

The most concrete explanation starts with a mechanism called an induction head. Researchers at Anthropic, led by Elhage and colleagues in 2021, identified a circuit inside transformers that does something simple and powerful. When it sees a token that appeared earlier in the sequence, it looks at what followed that token last time, and it boosts the probability of the same continuation now.

If the sequence contains "apple ... banana ... apple", an induction head helps the model predict "banana" after the second "apple". That is pattern completion in its purest form, and it is exactly what in-context learning needs at its core. The examples establish a pattern, the query sets up a new instance of it, and the induction mechanism completes it.

Induction heads form during training in a recognizable phase change: the model's loss drops suddenly as these circuits come online, and in-context learning ability appears at roughly the same time. The correlation is strong, and the mechanism is simple enough to verify directly by inspecting attention patterns. When researchers ablate induction heads, removing or disabling them, in-context learning degrades.

This explanation has a satisfying property: it is mechanistic rather than metaphorical. It points to actual circuits doing actual work. But it is also incomplete. Induction heads explain copying and completing repeated patterns, which covers translation pairs and classification labels. They do not obviously explain the harder cases, where the model has to infer an abstract rule from examples and apply it to something genuinely new, rather than completing a pattern it has already seen. A model that can learn a new function from five input-output pairs in the prompt is doing something richer than copying, and induction heads alone do not cover it.

Explanation two: the transformer runs a learning algorithm inside the forward pass

The second explanation is bolder. It says the forward pass itself implements a learning algorithm, and the prompt is the training data for that inner algorithm. The weights never change, but the activations behave as if a model were being trained on the examples and then applied to the query.

The evidence for this comes from a series of papers that trained small transformers on synthetic tasks and then examined what the networks had learned to do. Von Oswald and colleagues, in 2022, showed that a transformer trained on linear regression problems in context learns to implement something close to gradient descent in its layers: the attention mechanism computes updates that resemble the steps a gradient descent optimizer would take, and the model's predictions improve as more examples appear in the context, in the way a trained model improves with more training data. Dai and colleagues, in 2022, showed a similar result from a different angle, mapping the attention computation onto the form of a gradient descent update and finding that the correspondence held in real models, not just synthetic ones.

Put simply, the claim is that a transformer can be a learning algorithm and a model at the same time. The outer training, gradient descent on next-token prediction, produces an inner algorithm that itself learns from the context. This is sometimes called meta-learning, and it is not a new idea in machine learning. What is new is that it apparently emerged on its own, from training on text, without anyone designing the inner algorithm.

This explanation handles the harder cases better than induction heads do, because a learning algorithm can generalize from examples rather than just completing patterns. But it has its own problems. The demonstrations of gradient descent inside transformers are mostly on simple synthetic tasks, linear regression and similar, where the inner algorithm is easy to identify. For real language tasks, the correspondence is much harder to pin down, and nobody has shown a clean gradient descent circuit operating inside GPT-3 on a sentiment classification prompt. The explanation may be true in spirit and wrong in detail, or true for simple tasks and a poor description of the real ones. The field has not settled this.

Explanation three: the prompt is evidence about a hidden task

The third explanation comes from probability rather than circuits. It treats in-context learning as Bayesian inference. The model has learned, from pretraining, a distribution over many possible tasks, topics, and formats. A prompt is evidence about which of those latent tasks you mean. As the model reads the examples, it updates its beliefs about the task, and by the time it reaches the query, it has narrowed down to the right one and answers accordingly.

Xie and colleagues formalized this view in 2022. In their framing, pretraining data is a mixture of documents, each generated by some latent concept: a topic, a style, a task. The model learns the mixture. A prompt with examples is a sample from one component of the mixture, and the model infers which component produced it. More examples mean stronger evidence, which is why performance usually improves as you add examples, up to a point.

This explanation is attractive because it predicts several observed behaviors. It predicts that examples help even when their labels are not what matters most, which matches a finding we will come back to. It predicts that in-context learning works best when the task is one the model plausibly saw during pretraining, in some form, which is consistent with the observation that models are good at few-shot tasks that resemble common text formats and bad at tasks that do not. And it does not require any special mechanism: Bayesian inference over latent concepts is just what a good next-token predictor does.

The weakness of this explanation is that it is hard to falsify. Almost any behavior can be redescribed as inference over some latent variable, which means the explanation risks explaining everything and therefore nothing. Its value is as a framing: it tells you what to expect about when in-context learning will and will not work, and it connects in-context learning to the model's training data in a useful way. But it does not tell you which circuits do the work, and it does not by itself predict the failure modes.

What the evidence says it is not

These three explanations are not mutually exclusive. Induction heads may be one mechanism among several, gradient descent may describe what some layers do on some tasks, and the Bayesian view may describe the computation at a higher level. But the experiments also put limits on how much "learning" is really going on, and the limits are important.

The most cited result is from Min and colleagues, in 2022. They tested what actually matters in the demonstrations by corrupting them. They replaced the correct labels with random ones, keeping the format and the input distribution intact, and performance barely dropped on many tasks. The model did not seem to need the examples to be correct. What it needed was the format: the shape of the task, the distribution of the inputs, the label space. The examples were teaching the model what kind of thing to output, not what the mapping from inputs to outputs was. The mapping, apparently, the model already knew from pretraining.

That result complicates the "learning" story. If the model ignores wrong labels, it is not learning the task from the examples in the way a trained classifier learns from labeled data. It is retrieving something it already knows and using the examples to locate it. The follow-up literature has qualified this: on harder tasks, and on tasks the model genuinely has not seen, correct labels do matter more, and more recent models are more sensitive to label correctness than the models Min and colleagues studied. But the basic point stands. A large part of what in-context learning does is specification, not instruction. The examples tell the model which of its many capabilities to use, and in what format.

There are other limits that fit this picture. In-context learning is sensitive to the order of examples, with a recency bias toward the last ones, which is not how a real training set behaves. It is sensitive to the exact wording of the prompt, sometimes dramatically so, in ways that look more like pattern matching than learning. It can be misled by examples that are systematically wrong, and it has no memory: the adaptation lasts exactly one context window and then it is gone. None of this is fatal to the idea that in-context learning is real learning, but it is a reminder that the word "learning" is doing a lot of work, and that much of what happens may be closer to retrieval and specification than to the kind of learning that changes a model.

The connection to reasoning, and to diffusion

In-context learning is also the mechanism underneath chain-of-thought prompting, which I wrote about earlier in the context of test-time compute. When you ask a model to reason step by step, you are usually showing it examples of step-by-step reasoning, and the model continues the pattern. The reasoning ability, whatever it is, is being elicited by the context, not installed by training. That is why prompt design matters so much for reasoning tasks, and why the same model can look brilliant or foolish depending on what is in its context.

The same questions now arise for diffusion language models, which is where my own work sits. Diffusion models generate text by iterative refinement rather than left-to-right prediction, and their relationship to in-context learning is less studied. Early results suggest diffusion language models can also learn from examples in context, but the mechanism has to be different, because there is no autoregressive left-to-right pass for induction heads to operate in. Understanding how in-context adaptation works when generation is a denoising process rather than a sequence of predictions is an open question, and it is one of the reasons the broader question matters. If in-context learning is a property of next-token prediction specifically, then models that predict differently may learn differently. If it is a property of large models trained on diverse text, then it should show up everywhere, and the differences between architectures become a way of testing which explanation is right.

Why this matters

In-context learning matters first because it is the interface. Almost everything people do with language models, from chat to coding assistants to few-shot classification, runs through the prompt. Understanding what the prompt actually does to the model is understanding the tool most people use every day. When a prompt fails, the usual response is to add more examples or reword the instruction, and whether that helps depends on which explanation is right. If the examples are mostly specifying format, then adding more of them has diminishing returns, and the fix is a better description of the task. If the model is running an inner learning algorithm, then more examples should keep helping, and the fix is more or better data in the context.

It matters second because it changes how models are evaluated. A benchmark score for a language model is now usually a few-shot score, which means it measures the model plus the prompt. Two labs testing the same model with different prompts can get different numbers, and the difference is not noise, it is the capability itself being prompt-dependent. This is why evaluation has become so contentious, and why claims about a model being better than another need a careful look at how each was prompted.

It matters third because it is the closest thing we have to watching a model learn in real time. Training happens once, behind closed doors, over weeks. In-context learning happens in front of us, in a single forward pass, and we can intervene on it: change an example, reorder the prompt, corrupt a label, and watch the behavior change. That makes it a laboratory for the questions interpretability cares about. If we can work out what the model is doing when it adapts to a prompt, we will have learned something about what it does when it learns anything at all.

The honest summary is that the field does not yet know which explanation is right, and the answer is probably a combination: pattern completion circuits doing part of the work, something like an inner learning algorithm doing another part, and Bayesian inference over latent tasks describing the whole at a level above the circuits. What is not in doubt is the phenomenon itself. A model whose weights never change can behave as if it learned, and that fact alone rearranged how machine learning is done. The question now is not whether models learn in context. It is what, exactly, they are doing when they appear to.

References

  • Brown, T., et al. (2020). Language Models are Few-Shot Learners. arXiv:2005.14165. The GPT-3 paper, which introduced in-context learning as a capability of large language models.
  • Elhage, N., et al. (2021). A Mathematical Framework for Transformer Circuits. Anthropic. Induction heads and the circuit-level account of pattern completion in context.
  • Von Oswald, J., et al. (2022). Transformers Learn In-Context by Gradient Descent. arXiv:2212.07677. Evidence that transformers trained on synthetic tasks implement gradient descent in their forward pass.
  • Dai, D., et al. (2022). Why Can GPT Learn In-Context? Language Models Implicitly Perform Gradient Descent as Meta-Optimizers. arXiv:2212.10559. The mapping between attention and gradient descent updates in real models.
  • Xie, S. M., et al. (2022). An Explanation of In-Context Learning as Implicit Bayesian Inference. arXiv:2111.02080. The Bayesian view of prompts as evidence about a latent task.
  • Min, S., et al. (2022). Rethinking the Role of Demonstrations: What Makes In-Context Learning Work? arXiv:2202.12837. Corrupted-label experiments showing that format and input distribution matter more than correct labels.
  • Wei, J., et al. (2022). Chain-of-Thought Prompting Elicits Reasoning in Large Language Models. arXiv:2201.11903. Reasoning elicited through examples in the prompt.
  • Chan, S., et al. (2022). Data Distributional Properties Drive Emergent In-Context Learning in Transformers. arXiv:2205.05055. Which properties of training data make in-context learning emerge.
📰 Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.