In-Context Learning
Suppose you want a language model to translate slang into formal English. But you have no training pipeline, no labeled dataset, and no time to fine-tune. You simply write three examples of slang-to-formal pairs into the prompt. Then you add a fourth slang sentence, and the model produces the correct translation. No gradient ever touched the weights. This phenomenon, called in-context learning (ICL), is one of the most consequential discoveries in modern natural language processing. It turns a single frozen model into a general-purpose reasoning engine. That engine adapts to new tasks at inference time. In-context learning matters because it collapses the traditional machine learning pipeline. Classic supervised learning requires collecting data, choosing a loss function, running backpropagation, and deploying a new model checkpoint for every task. ICL replaces all of that with writing a prompt. This is the mechanism underlying most practical uses of large language models today: few-shot classification, structured data extraction, code generation from examples, and much of what is loosely called "prompt engineering." Understanding ICL precisely is essential before studying prompting techniques or chain-of-thought reasoning. This means knowing what it is, how it differs from ordinary learning, and why it emerges from large-scale pretraining. Both prompting and chain-of-thought reasoning are specific strategies for exploiting the ICL capability. The big picture is this: a Transformer language model is trained purely to predict the next token on massive text corpora. As a side effect, it acquires the ability to infer a task's input-output mapping. It does this from a handful of demonstrations placed in its context window. The model's parameters never change. Instead, the sequence of tokens in the prompt implicitly configures the model's forward computation. This makes it behave like a task-specific predictor. This is sometimes described as the model performing an implicit optimization procedure inside its own forward pass. This is a claim with real theoretical and empirical support, one this article examines carefully. This article gives a precise definition of in-context learning. It distinguishes ICL from fine-tuning and meta-learning. It walks through the exact mechanics of how a prompt is constructed and consumed by the model. It presents the leading theoretical accounts of why it works. These include the Bayesian inference view and the induction-head/gradient-descent-in-attention view. It analyzes the complexity of running ICL at inference time. It also works through a fully traced numerical example. It closes with common failure modes, the history of the discovery, and where ICL is used in deployed systems.
- In-context learning (ICL) is task adaptation via examples placed in the prompt, with zero updates to model weights.
- It emerges from large-scale next-token pretraining; it becomes reliable only past a certain model scale, echoing Emergent Abilities & Scaling Laws.
- Mechanically, ICL is nothing but a forward pass: demonstrations are concatenated tokens, and attention lets the model condition on them.
- Two major theories explain it: ICL as implicit Bayesian inference over a latent task, and ICL as implicit gradient descent performed by attention layers.
- Inference cost scales at least linearly (attention: quadratically without caching tricks) in the number of demonstration tokens, unlike fine-tuning's one-time training cost.
- ICL is brittle to example order, label format, and selection, which motivates the more disciplined study of Prompting & Prompt Engineering and Chain-of-Thought Reasoning.
In-context learning lets a frozen model infer a new task's rule purely from examples written into its input, by reusing its pretrained forward computation as an implicit learning algorithm — no parameter update required.
The idea
In-context learning is the ability of a pretrained autoregressive language model to perform a new task after conditioning on a prompt containing a task description and/or a small number of input-output demonstrations, with the model's parameters held completely fixed. Formally, given a sequence of demonstrations and a new query , the model computes
where is the same conditional distribution the model uses for ordinary next-token prediction. Nothing about the architecture or the training objective changes; the "learning" happens entirely inside a single forward pass, driven by the content of the context window. This is why the number of demonstrations is called the shot count: is zero-shot prompting, is one-shot, and is few-shot. It is crucial to separate ICL from three superficially similar ideas. Fine-tuning updates via gradient descent on task-specific data; ICL updates nothing. Meta-learning (e.g., MAML) explicitly trains a model, across many tasks, to be good at rapid adaptation via a few gradient steps at test time; ICL requires no such specialized meta-training objective — it emerges from vanilla next-token prediction on internet-scale text, though the diversity of that text plausibly makes pretraining resemble an implicit multi-task curriculum. Retrieval-augmented generation fetches external documents to append to the prompt; this can supply demonstrations for ICL but is a separate mechanism for sourcing content, not the learning mechanism itself. The prompt used for ICL typically has three components: an optional natural-language instruction, a set of demonstrations formatted consistently (e.g., `Input: ... \n Output: ...`), and the query. The consistency of formatting matters enormously, because the model is pattern-matching the structure of the demonstrations as much as their content — a fact that motivates the careful craft discussed under Prompting & Prompt Engineering.
How it works
Mechanically, ICL requires no special machinery beyond a standard Transformer decoder — the "algorithm" is just careful prompt construction followed by a single forward pass and greedy or sampled decoding. What differs from ordinary generation is how the prompt is built and how the output is extracted and scored.
Step 1 — Task framing. Choose a natural-language instruction (optional) and decide on the answer format (e.g., a single word, a label from a fixed set, a JSON object).
Step 2 — Demonstration selection. Choose example pairs that are representative of the mapping to be learned. In practice these are drawn from a labeled pool, sometimes selected to be similar to the query (nearest-neighbor retrieval) to improve accuracy.
Step 3 — Demonstration ordering and formatting. Concatenate the examples into a single string using a fixed template, then append the query with the output slot left blank.
Step 4 — Forward pass. Feed the full prompt through the Transformer. Every token — instruction, demonstration inputs, demonstration labels, and query — is embedded and processed by self-attention across all preceding tokens (causal masking permitting only left-to-right attention).
Step 5 — Decoding. Read off at the answer position(s), and decode (greedily, via sampling, or by scoring a fixed candidate set and picking the highest-probability candidate — useful for classification tasks with a known label set).
Step 6 (optional) — Calibration. Because raw next-token probabilities can be skewed by surface-form frequency (e.g., "positive" being a common word regardless of task), practitioners sometimes recalibrate by comparing to the model's output on a content-free query. ``` function IN_CONTEXT_LEARNING(instruction, demonstrations, query, model, label_set = None):
# demonstrations: list of (x_i, y_i) pairs
# Step 1-3: build the prompt string prompt = instruction + "\n" for (x_i, y_i) in demonstrations: prompt += format_input(x_i) + format_output(y_i) + "\n" prompt += format_input(query) # leave output slot open tokens = TOKENIZE(prompt) # length n if n > model.context_window: error "prompt exceeds context window" # hard constraint
# Step 4: single forward pass (no gradient computation, no weight update) hidden_states = model.FORWARD(tokens) # causal self-attention, O(n^2) naive logits = model.OUTPUT_HEAD(hidden_states[-1]) # distribution over vocabulary
# Step 5: decode if label_set is None: y_hat = GREEDY_OR_SAMPLE_DECODE(model, tokens) # free-form generation else:
# classification-style scoring: pick the label with highest sequence log-prob best_label, best_score = None, -infinity for label in label_set: score = LOG_PROB(model, tokens ++ TOKENIZE(label)) if score > best_score: best_label, best_score = label, score y_hat = best_label return y_hat ``` The pseudocode is deliberately unremarkable: that is the point. There is no learning-rate schedule, no loss function, no optimizer state. The entire "few-shot learner" is the frozen function `model.FORWARD` combined with a carefully chosen input string. All of the interesting behavior is a property of what happened during pretraining, not of any code written here.
Complexity & correctness
Time complexity. Let be the total prompt length in tokens (instruction + demonstrations + query) and the number of Transformer layers with hidden dimension . A single forward pass costs
— the term from self-attention (each of query positions attends to up to key positions, each attention operation costing ), and the term from the feed-forward and projection sublayers applied at each position. Adding one more demonstration of length tokens increases by , so the marginal cost of the -th shot grows the quadratic term roughly linearly in per added token, meaning total cost grows roughly quadratically in the number of shots if each shot has fixed length. In deployed systems, key-value caching lets the demonstration prefix be processed once and reused for multiple queries, amortizing this cost when many queries share the same few-shot prompt; generation of the answer itself, token by token, costs per new token with caching (versus recomputing the full attention from scratch without it). Contrast this with fine-tuning: gradient-based adaptation costs for epochs over a dataset of size , paid once, after which inference is cheap and prompt-length-independent. ICL pays no training cost but re-pays an inference-time cost — proportional to per query — every single time the task is invoked, unless caching is used. This is the central efficiency tradeoff: ICL trades upfront training cost for recurring, prompt-length-dependent inference cost, and is advantageous when the task changes frequently or training data is too scarce to fine-tune on, but is disadvantageous at very high query volume for a fixed task.
Space complexity. The KV cache for a prompt of length requires memory (two matrices, keys and values, per layer, per token). This is why long few-shot prompts with many demonstrations directly compete with the model's context-window budget and memory footprint — a real deployment constraint, not just an abstraction.
Correctness — why does it work at all? There is no single proof that ICL "is correct" in the sense of a sorting algorithm; instead there are two complementary explanations, each with supporting theoretical and empirical evidence. View 1: ICL as implicit Bayesian inference. Pretraining on a diverse text corpus can be modeled as training on a mixture of latent "concepts" or tasks . The pretraining objective — next-token prediction — implicitly forces the model to learn
When a prompt contains several demonstrations consistent with a single latent task , the posterior concentrates on as more demonstrations are added (each additional example is further evidence, in the Bayesian-updating sense), sharpening the model's implicit prediction. This view — supported by work formalizing pretraining as latent-variable model estimation and by controlled synthetic experiments (e.g., Hidden Markov Model-generated data with recoverable latent tasks) — correctly predicts that ICL accuracy should increase with number of demonstrations, that low-diversity demonstrations concentrate the posterior faster, and that models can perform ICL even on tasks with example distributions unlike anything in pretraining, as long as the format triggers task-identification. View 2: ICL as implicit gradient descent in attention. A separate line of theoretical work shows that a linear self-attention layer, given a prompt of demonstrations, can be constructed (and is empirically approximated by trained Transformers) to perform an update mathematically equivalent to one step of gradient descent on a linear regression loss fit to the in-context demonstrations. Concretely, for a linear attention layer with appropriately structured weight matrices, the layer's output on the query equals
for an implicit learning rate determined by the attention weights — i.e., the forward pass literally computes what one gradient step of an outer optimizer would compute, using the demonstrations as the training set for that single step. This is a constructive existence proof (such attention weights exist and are reachable by training) rather than a proof that all Transformers learn this exact mechanism, but empirically the predictions and even the intermediate activations of trained models match this gradient-descent construction closely on synthetic regression tasks. It aligns with the discovery of induction heads — attention heads that specifically implement a "copy the token that followed the last occurrence of the current token" operation, which is exactly the primitive needed to complete a pattern established by demonstrations. Neither theory is fully general, and both are honestly incomplete for the full range of real-world ICL behavior (arbitrary natural-language tasks, non-linear mappings, multi-step reasoning). What is well established empirically and theoretically is: (1) ICL performance improves with model scale in a manner tightly linked to Emergent Abilities & Scaling Laws, (2) ICL performance improves (with diminishing returns, and occasional degradation from long-context effects) with more demonstrations, and (3) ICL is genuinely doing conditional inference over the prompt, not simple memorized lookup, since it generalizes to label mappings never seen during pretraining (e.g., flipped or randomized labels in controlled studies still shift model behavior, showing sensitivity to the actual demonstration content, though performance often degrades relative to correct labels — evidence that both the input-output format and label correctness both matter, and their relative contribution is task-dependent).
Worked example
Consider a sentiment-classification task the model was never explicitly fine-tuned for: classifying restaurant reviews as `POS` or `NEG`. We build a 3-shot prompt.
Prompt constructed: ``` Classify the sentiment of the review as POS or NEG. Review: The service was slow but the food made up for it. Sentiment: POS Review: Cold soup, rude waiter, and we waited 40 minutes. Sentiment: NEG Review: Portions were tiny and overpriced for what we got. Sentiment: NEG Review: Best pasta I've had all year, will absolutely return. Sentiment: ``` Trace through the pipeline:
| Step | What happens | Concrete value |
|---|---|---|
| Tokenize | Prompt converted to token IDs | tokens |
| Forward pass | Causal self-attention over all 78 positions, layers | FLOPs, single pass |
| Induction signal | Attention heads at later layers find prior occurrences of the pattern "Review: ... \n Sentiment: X" and copy the structural role of X | pattern-completion, not memorized lookup |
| Posterior concentration | After 3 demonstrations all consistent with a binary sentiment task, is sharply peaked on "binary sentiment classification with labels POS/NEG" | latent task inferred |
| Candidate scoring | Model computes vs. | e.g. , |
| Decode | Greedy / argmax over the two candidates | `POS` selected |
| Output | Model emits | `POS` |
Now perturb the experiment to test robustness, which is the standard way researchers probe why ICL is working rather than merely memorizing surface strings:
- Swap labels randomly (demonstration 1 relabeled NEG despite positive content): accuracy on new queries typically drops, but does not collapse to chance for large models — evidence the model partially relies on prior semantic knowledge of "sentiment," not purely on the mapping shown.
- Keep labels correct but change the label tokens to arbitrary symbols (`Sentiment: Foo` / `Sentiment: Bar`): large models can still learn the mapping correctly from the pattern alone, showing the mechanism generalizes beyond memorized label words — strong evidence for genuine in-context pattern induction, not lookup of familiar words.
- Increase shots from 3 to 20: accuracy improves with diminishing returns, consistent with the Bayesian posterior-concentration account, though very long prompts can sometimes hurt accuracy due to attention dilution or recency bias (the model over-weighting the last few demonstrations) — a documented practical failure mode.
Common pitfalls & traps
| Pitfall | Why it happens | Fix |
|---|---|---|
| Sensitivity to example order | Attention and positional effects make later demonstrations more influential (recency bias); different permutations of the same examples can shift accuracy by tens of points | Try multiple orderings, average predictions, or select an order via a held-out validation set |
| Sensitivity to formatting | The model pattern-matches surface template as much as content; a stray extra newline or inconsistent label casing can degrade performance | Keep templates rigidly consistent across all demonstrations and the query |
| Label imbalance in demonstrations | If 3 of 4 demonstrations are the same label, the model's output distribution is biased toward the majority label regardless of the query | Balance labels across the shown demonstrations |
| Treating ICL as memorized fact retrieval | Confusing "the model already knows the answer" with "the model learned the mapping from the prompt" inflates perceived capability | Test with label permutations or synthetic label sets absent from pretraining data |
| Ignoring context-window and cost limits | Adding many long demonstrations silently costs quadratic attention compute and can truncate the prompt | Budget token count explicitly; use retrieval to select the most useful few shots, not the most shots |
| Assuming monotonic gains from more shots | Very long prompts can reduce accuracy due to attention dilution, distractor demonstrations, or exceeding effective context length | Empirically validate the shot count on a held-out set rather than assuming "more is better" |
Pioneers & history
Origins · 1 minTom B. Brown and how this was discovered
physicist[Alec Radford|active researcher, OpenAI, 2010s–2020s|Co-developed GPT-2 and GPT-1, demonstrating that generative pretraining on raw text alone yields transferable task capability, laying the empirical groundwork that culminated in explicit few-shot in-context learning with GPT-3.]
Origins · 1 minhow this was discovered
Where this matters
In-context learning underlies nearly every practical interaction with a modern large language model API. Customer-support automation systems inject a handful of example resolved tickets into a prompt to adapt a single deployed model to a company's specific tone and policies, without any fine-tuning pipeline. Structured data extraction tools (turning unstructured text into JSON records) rely on few-shot examples in the prompt to specify the exact schema desired. Code assistants use in-context examples of a repository's coding style or API usage patterns to generate consistent completions. Evaluation benchmarks for new foundation models almost universally report both zero-shot and few-shot (in-context) scores, since the gap between them is itself a diagnostic of model quality and scale. The technique also underlies retrieval-augmented generation systems, where retrieved documents function as in-context "demonstrations" or evidence the model conditions on at inference time. Finally, ICL is the substrate on which more sophisticated prompting strategies are built — Prompting & Prompt Engineering studies how to construct better in-context examples and instructions, and Chain-of-Thought Reasoning studies a special case of in-context demonstration where the shown examples include intermediate reasoning steps rather than only final answers, dramatically improving performance on multi-step problems.
Ask the tutor: Why does adding more few-shot examples sometimes hurt accuracy instead of helping it?
Does in-context learning actually change the model's weights, even temporarily?
No. The parameters of the model are completely unchanged before, during, and after processing a few-shot prompt. What changes is the activations computed during the forward pass — the hidden states and attention patterns produced from the specific token sequence in the prompt. Some theoretical work shows that certain attention layers can be interpreted as implicitly computing something mathematically equivalent to a gradient-descent update, but this is a property of the fixed forward computation applied to the demonstration tokens, not an actual write to persistent parameters. If you start a fresh conversation, the model has no memory of the prior prompt's demonstrations unless you re-include them.
Why does in-context learning only become reliable at larger model scales?
Smaller models often show flat or inconsistent few-shot curves — sometimes even negative slopes, where more demonstrations hurt performance — while larger models show smooth, often near-monotonic improvement with more shots. The leading explanation is that ICL requires the model to have learned rich enough internal machinery (such as induction heads, which reliably emerge only past certain scale and training-data thresholds) to detect and continue an in-context pattern. This scale-dependence is exactly the kind of qualitative capability shift studied under Emergent Abilities & Scaling Laws, and it is one of the most cited pieces of evidence in that literature.
Is in-context learning the same thing as meta-learning like MAML?
They are related in spirit but distinct in mechanism. Meta-learning approaches like MAML explicitly optimize a model, across a distribution of tasks during training, so that a few real gradient steps at test time adapt it well to a new task. ICL requires no explicit multi-task meta-training objective — it is an emergent byproduct of ordinary next-token prediction pretraining on diverse text, and it requires zero gradient steps at test time. Some researchers describe the diversity of pretraining text as implicitly resembling a meta-learning curriculum, which is a plausible partial explanation for why ICL emerges, but the training objective itself is unchanged from standard language modeling.
Does the correctness of the labels in the demonstrations actually matter, or is the model just recognizing the task format?
Both matter, and their relative contribution is task- and scale-dependent. Controlled experiments that randomize or flip the labels in demonstrations show that large models' accuracy typically drops but does not fall all the way to chance level, indicating the model leans partly on prior knowledge of the task (e.g., knowing what "positive sentiment" generally looks like) independent of the exact labels shown. At the same time, changing label tokens to novel symbols while keeping the label-to-input mapping consistent and correct often preserves high accuracy, showing the model genuinely uses the demonstrated mapping, not just memorized label words. The honest conclusion is that ICL blends prior task knowledge with genuine conditioning on the specific demonstrations.
How many demonstrations should I use in practice?
There is no universal answer; it depends on task difficulty, demonstration quality, and context-window budget. Empirically, accuracy tends to improve with more shots up to a point, with diminishing returns, and can even degrade beyond some threshold due to attention dilution, distracting or redundant examples, or recency bias toward the last few shots. The practical recipe is to treat shot count as a hyperparameter: evaluate a small held-out validation set across several shot counts (e.g., 0, 1, 4, 8, 16) and pick the setting that generalizes best, rather than assuming more examples are always better.
Can in-context learning solve tasks the model never saw anything like during pretraining?
To a real but limited extent. If the format (input-output structure, reasoning pattern) resembles something in the pretraining distribution, even with entirely novel content or symbols, the model can often perform well, because the mechanism operates on structural pattern-completion, not literal memorized answers. However, ICL cannot substitute for genuinely new capabilities the model's pretraining never equipped it with — for example, no amount of clever few-shot prompting will let a model correctly perform arithmetic far outside the numeric ranges it can reliably handle, or execute algorithms requiring more working memory than its context and attention mechanisms can support.
How does in-context learning relate to prompt engineering and chain-of-thought reasoning?
In-context learning is the underlying capability; prompting techniques are strategies that exploit it. Prompting & Prompt Engineering is the practical discipline of designing instructions, demonstrations, and formatting to maximize the model's task performance via ICL. Chain-of-Thought Reasoning is a specific, especially powerful prompting strategy: instead of demonstrations that show only input-output pairs, the demonstrations include the intermediate reasoning steps leading to the answer, which the model then imitates for the query, substantially improving performance on multi-step arithmetic, logic, and commonsense reasoning tasks.