Simple Algorithm
Artificial Intelligence · Deep Layer · 28 min

In-Context Learning & Emergence

Learning from the prompt, and whether abilities “emerge”.

Show a pretrained model three examples of a task it was never trained on, and it often does the fourth. No weight changes: the "learning" happens inside a forward pass. This lesson examines three explanations (Bayesian inference over latent concepts, gradient descent carried out by attention, and induction circuits) and the debate over whether such abilities appear suddenly with scale.

What you’ll learn

  • Define in-context learning precisely, and summarize what experiments show about which parts of a prompt matter.
  • Derive posterior concentration in a mixture model, the core of the implicit-Bayesian-inference account.
  • Prove that one linear self-attention layer can implement a gradient-descent step on in-context least squares, and describe induction heads and the evidence for them.
  • Analyze how exact-match metrics turn smooth per-token progress into apparent emergence, and weigh the evidence on both sides.

What in-context learning is, and what matters

Landmark findings, which any explanation must accommodate:

  • Scale and function classes. GPT-3's few-shot gains grew with model size (Brown et al., 2020). Transformers trained from scratch on prompts of (xi,f(xi))(\mathbf x_i,f(\mathbf x_i)) pairs learn whole function classes in context, such as linear functions in 20 dimensions, about as well as least squares (Garg et al., 2022).
  • Labels matter less than expected, at first. In classification and multiple choice, replacing demonstration labels with random ones barely hurt a range of models; the input distribution, the label space and the format mattered more (Min et al., 2022). Yet larger models can override their priors: given flipped labels they follow the flips, and they can learn semantically unrelated label mappings (Wei et al., 2023).
  • Fragility. Accuracy can swing widely with the order of the same demonstrations (Lu et al., 2022) and with the choice of examples and template, partly because models favor labels that are frequent or recent in the prompt (Zhao et al., 2021).
  • Data. In-context learning emerges during training when data are "bursty", with items recurring within a context, and long-tailed, and it competes with storing knowledge in the weights (Chan et al., 2022).

In-context learning as implicit Bayesian inference

Xie et al. (2022) model pretraining documents as a mixture: draw a latent concept θ∼π\theta\sim\pi (in their analysis, the parameters of a hidden Markov model), then a document from p(⋅∣θ)p(\cdot\mid\theta). A model that predicts the next token optimally must marginalize over concepts, so it implicitly computes a posterior:

p(y∣Sk,x)=∑θp(y∣x,θ) π(θ∣Sk,x),π(θ∣Sk)∝π(θ)∏i=1kp(xi,yi∣θ)p(y\mid S_k,x)=\sum_\theta p(y\mid x,\theta)\,\pi(\theta\mid S_k,x),\qquad\pi(\theta\mid S_k)\propto\pi(\theta)\prod_{i=1}^kp(x_i,y_i\mid\theta)
The second form treats demonstrations as independent given θ\theta. Real prompts are concatenations of independent examples joined by delimiters, which pretraining documents rarely are; Xie et al. handle that mismatch explicitly.
DerivationPosterior concentration
  1. log⁡π(θ∣Sk)π(θ⋆∣Sk)=log⁡π(θ)π(θ⋆)+∑i=1klog⁡p(xi,yi∣θ)p(xi,yi∣θ⋆)\log\frac{\pi(\theta\mid S_k)}{\pi(\theta^\star\mid S_k)}=\log\frac{\pi(\theta)}{\pi(\theta^\star)}+\sum_{i=1}^k\log\frac{p(x_i,y_i\mid\theta)}{p(x_i,y_i\mid\theta^\star)}

    Let the demonstrations be i.i.d. from concept θ⋆\theta^\star, with Θ\Theta finite. For any other θ\theta, the log posterior odds are the prior odds plus a sum of log-likelihood ratios:

  2. 1k∑i=1klog⁡p(xi,yi∣θ)p(xi,yi∣θ⋆) →a.s. −DKL(p(⋅∣θ⋆) ∥ p(⋅∣θ))<0\frac1k\sum_{i=1}^k\log\frac{p(x_i,y_i\mid\theta)}{p(x_i,y_i\mid\theta^\star)}\ \xrightarrow{\text{a.s.}}\ -\KL\big(p(\cdot\mid\theta^\star)\,\big\|\,p(\cdot\mid\theta)\big)<0

    By the strong law of large numbers the average log-ratio converges to minus a KL divergence, which is positive whenever θ\theta is distinguishable from θ⋆\theta^\star:

  3. π(θ∣Sk)≤π(θ)π(θ⋆) e−k(KL−ϵ)⟹p(y∣Sk,x)→p(y∣x,θ⋆)\pi(\theta\mid S_k)\le\frac{\pi(\theta)}{\pi(\theta^\star)}\,e^{-k(\mathrm{KL}-\epsilon)}\quad\Longrightarrow\quad p(y\mid S_k,x)\to p(y\mid x,\theta^\star)

    So for any ϵ>0\epsilon>0 the odds of every wrong concept eventually fall below e−k(KL−ϵ)e^{-k(\mathrm{KL}-\epsilon)}, the posterior concentrates on θ⋆\theta^\star, and the predictive distribution converges to the Bayes-optimal prediction for the prompt's task:

  4. Xie et al.'s theorem adds the delimiters: each boundary between examples is a low-probability transition under every concept and contributes an error term. If the per-example KL separation exceeds it (their distinguishability condition), in-context predictions still become Bayes-optimal as k→∞k\to\infty. On a synthetic dataset built this way (GINC), small transformers and LSTMs learn in context, better with more and longer examples.

The Bayesian view explains several findings: demonstrations mainly identify the task, so format and input distribution matter even with random labels, and a strong prior can outvote a few contrary examples. It describes the function computed, not a mechanism. Whether trained models are near Bayes-optimal under a realistic prior is empirical. On regression prompts, transformers pretrained on few distinct tasks behave like the Bayes estimator for that finite set, while past a threshold of task diversity they behave like ridge regression and solve genuinely new tasks (Raventós et al., 2023).

Mechanisms: gradient descent and induction heads

DerivationProof
  1. ∇L(0)=−1k∑iyixi ⟹ w1=ηk∑iyixi,y^q=w1⊤xq=ηk∑iyi xi⊤xq\nabla L(\mathbf 0)=-\frac1k\sum_iy_i\mathbf x_i\ \Longrightarrow\ \mathbf w_1=\frac\eta k\sum_iy_i\mathbf x_i,\qquad\hat y_q=\mathbf w_1^\top\mathbf x_q=\frac\eta k\sum_iy_i\,\mathbf x_i^\top\mathbf x_q

    One step with learning rate η\eta from w0=0\mathbf w_0=\mathbf 0:

  2. WKei=xi,WQeq=xq,WVei=(0, ηk yi)W_K\mathbf e_i=\mathbf x_i,\qquad W_Q\mathbf e_q=\mathbf x_q,\qquad W_V\mathbf e_i=\big(\mathbf 0,\ \tfrac\eta k\,y_i\big)

    Choose WKW_K and WQW_Q to keep only the x\mathbf x-part of a token, and WVW_V to move ηk yi\tfrac\eta k\,y_i into the yy-slot:

  3. eq ⟼ (xq, ηk∑i=1kyi xi⊤xq)=(xq, y^q)\mathbf e_q\ \longmapsto\ \Big(\mathbf x_q,\ \frac\eta k\sum_{i=1}^ky_i\,\mathbf x_i^\top\mathbf x_q\Big)=(\mathbf x_q,\ \hat y_q)

    The update adds (0,ηk∑iyi xi⊤xq)\big(\mathbf 0,\tfrac\eta k\sum_iy_i\,\mathbf x_i^\top\mathbf x_q\big) to the query token, which is exactly y^q\hat y_q. Layers that also update the context tokens' residuals yi−w⊤xiy_i-\mathbf w^\top\mathbf x_i take further steps.

Linear self-attention layers trained on such regression prompts converge to this construction or a preconditioned variant (von Oswald et al., 2023); for one layer, the global optimum of training is provably a preconditioned gradient step (Ahn et al., 2023); and trained transformers move between gradient-descent-like, ridge and least-squares predictors as depth and noise vary (Akyürek et al., 2023). Whether language models trained on natural text do anything similar on real tasks is contested (Shen, Mishra & Khashabi, 2024): the constructions are existence proofs in a stylized setting.

Induction heads are the best-documented mechanism in real models. An induction head completes [A][B] … [A] → [B]: at a token A it attends to the token that followed an earlier A and raises that token's logit. It takes two heads composed across layers (Elhage et al., 2021). A previous-token head in an earlier layer writes each token's predecessor into its position; the induction head's QK circuit matches the current token against those stored predecessors (K-composition), and its OV circuit copies the attended token to the output.

Olsson et al. (2022) gave six lines of evidence that induction heads drive much of in-context learning. Early in training, during a sharp phase change, induction heads form just as the in-context learning score (loss on the 500th token of a context minus loss on the 50th) jumps, visible as a bump in the training loss. Architecture changes that move the formation of induction heads move the jump with them. Ablating induction heads at test time removes most in-context learning in small attention-only models. In large models the evidence is correlational, and the same heads also do fuzzier pattern completion, such as copying across languages.

Check your understanding

In the text "… Harry Potter … Harry", what does an induction head do at the second "Harry"?

  1. It attends to the first "Harry" and copies "Harry"
  2. It attends to "Potter", the token after the earlier "Harry", and raises the probability of "Potter"
  3. It attends to the previous token and copies it
  4. It attends uniformly and averages the context
Show the answer

B. It attends to "Potter", the token after the earlier "Harry", and raises the probability of "Potter"

Prefix matching finds earlier positions whose predecessor was "Harry", and the OV circuit copies the token found there. The previous-token head in an earlier layer is what stored "my predecessor was Harry" at the position of "Potter".

Emergence: real, or an artifact of the metric?

Schaeffer, Miranda and Koyejo (2023) argued that much of this comes from the metric. Suppose an answer has LL tokens and the model gets each right with probability pp, which improves smoothly with scale. Exact match needs all of them:

DerivationSmooth per-token progress, sharp exact match
  1. EM=pL=e−Lℓ,ℓ=−log⁡p  (per-token loss on the answer)\mathrm{EM}=p^L=e^{-L\ell},\qquad\ell=-\log p\ \ \text{(per-token loss on the answer)}

    Treat token errors as independent. Exact-match accuracy is then a steep power of per-token accuracy:

  2. d EMdp=L pL−1\frac{d\,\mathrm{EM}}{dp}=L\,p^{L-1}

    With L=10L=10: p=0.5p=0.5 gives 0.1%0.1\%, 0.70.7 gives 2.8%2.8\%, 0.80.8 gives 10.7%10.7\%, 0.90.9 gives 34.9%34.9\% and 0.990.99 gives 90.4%90.4\%. On a linear axis with few model sizes, a smooth rise in pp looks like nothing, then a jump, and the steepness grows with LL:

  3. Under continuous metrics (log-likelihood, token edit distance, Brier score), the same model families improved smoothly and predictably on many of the reported tasks. Schaeffer et al. could even produce "emergent" curves in vision models just by choosing discontinuous metrics.

Predict before you look

An answer has L=20L=20 tokens, and per-token accuracy rises from p=0.90p=0.90 to p=0.95p=0.95 between two model sizes. What is exact-match accuracy at p=0.95p=0.95, in percent?

Show the answer

36 %

0.9520≈0.3580.95^{20}\approx0.358, up from 0.9020≈0.1220.90^{20}\approx0.122: halving the per-token error triples the headline accuracy.

The debate is not settled. The metric that matters in deployment is often the all-or-nothing one (a program runs or it does not), so a sharp rise in it is real for users even when the underlying progress is smooth. Measuring tiny success probabilities with many samples shows steady, predictable progress for many tasks long before accuracy leaves zero, though some rise faster than a smooth trend predicts (Hu et al., 2024). And genuine phase changes do occur during training, such as induction-head formation and grokking (Power et al., 2022). The quanta model of Scaling Laws offers a middle ground: individual skills switch on sharply while their average is smooth. As of the mid-2020s, whether a given capability will appear at a given scale cannot be reliably predicted.

Key takeaways

  • In-context learning lowers risk as demonstrations are added, with weights fixed. Demonstrations mainly identify the task, so format and input distribution matter, yet larger models can follow flipped or arbitrary labels.
  • In a mixture of latent concepts each demonstration adds a log-likelihood ratio, so wrong concepts' odds decay like e−k KLe^{-k\,\mathrm{KL}} and predictions become Bayes-optimal for the prompt's concept (Xie et al., 2022).
  • One linear attention layer can compute a gradient step on in-context least squares; induction heads, a previous-token head composed with a prefix-matching copying head, are the best-documented mechanism, with causal evidence in small models.
  • Exact match pLp^L turns smooth per-token progress into apparent jumps (Schaeffer et al., 2023). Whether some abilities are genuinely abrupt in scale is contested; phase changes during training are real.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

In the mixture-of-concepts view, why does the posterior concentrate on the prompt's concept as the number of demonstrations kk grows?

  1. Each demonstration updates the model's weights
  2. Each demonstration adds a log-likelihood ratio whose average tends to −DKL(pθ⋆ ∥ pθ)<0-\KL(p_{\theta^\star}\,\|\,p_\theta)<0, so wrong concepts' odds decay like e−k KLe^{-k\,\mathrm{KL}}
  3. The prior over concepts is uniform
  4. Delimiters make every concept equally likely
Show the answer

B. Each demonstration adds a log-likelihood ratio whose average tends to −DKL(pθ⋆ ∥ pθ)<0-\KL(p_{\theta^\star}\,\|\,p_\theta)<0, so wrong concepts' odds decay like e−k KLe^{-k\,\mathrm{KL}}

Posterior odds multiply across independent demonstrations, so their logarithm is a sum whose mean is negative for any distinguishable wrong concept.

Question 2

In von Oswald et al.'s construction, what does one linear self-attention layer compute at the query token?

  1. The least-squares solution (X⊤X)−1X⊤y(X^\top X)^{-1}X^\top\mathbf y applied to xq\mathbf x_q
  2. The average of the demonstration labels
  3. The label of the nearest demonstration
  4. The prediction ηk∑iyi xi⊤xq\frac\eta k\sum_iy_i\,\mathbf x_i^\top\mathbf x_q of one gradient step from w0=0\mathbf w_0=\mathbf 0
Show the answer

D. The prediction ηk∑iyi xi⊤xq\frac\eta k\sum_iy_i\,\mathbf x_i^\top\mathbf x_q of one gradient step from w0=0\mathbf w_0=\mathbf 0

Keys and queries carry x\mathbf x, values carry ηkyi\tfrac\eta ky_i, and linear attention sums value times key–query product: w1⊤xq\mathbf w_1^\top\mathbf x_q with w1=−η∇L(0)\mathbf w_1=-\eta\nabla L(\mathbf 0).

Question 3

Which piece of evidence for induction heads as a mechanism of in-context learning is causal rather than correlational?

  1. Ablating induction heads at test time removes most in-context learning in small attention-only models
  2. Induction heads and the in-context learning score both change abruptly early in training
  3. Large models contain heads that behave like induction heads
  4. In-context learning improves with model size
Show the answer

A. Ablating induction heads at test time removes most in-context learning in small attention-only models

An ablation intervenes on the mechanism and measures the effect. Co-occurrence in training and the presence of similar heads in large models fit the hypothesis but could have other causes, as Olsson et al. note.

Question 4

Per-token accuracy on 10-token answers improves smoothly from 0.800.80 to 0.950.95 across model sizes. Why might a plot of exact-match accuracy look emergent?

  1. Because the model suddenly learns a new algorithm at some size
  2. Because per-token accuracy cannot improve smoothly
  3. Because exact match is p10p^{10}, which climbs from about 11% to 60%: a steep nonlinear function of a smooth input
  4. Because larger models memorize the test set
Show the answer

C. Because exact match is p10p^{10}, which climbs from about 11% to 60%: a steep nonlinear function of a smooth input

0.810≈0.110.8^{10}\approx0.11 and 0.9510≈0.600.95^{10}\approx0.60. A threshold metric amplifies smooth progress into an apparent jump, the core of Schaeffer et al.'s argument; it does not prove that no ability is ever abrupt.

Further reading

  • S. M. Xie, A. Raghunathan, P. Liang & T. Ma, "An explanation of in-context learning as implicit Bayesian inference," ICLR (2022).
  • J. von Oswald, E. Niklasson, E. Randazzo, J. Sacramento, A. Mordvintsev, A. Zhmoginov & M. Vladymyrov, "Transformers learn in-context by gradient descent," ICML (2023).
  • C. Olsson et al., "In-context learning and induction heads," Transformer Circuits Thread (2022).
  • R. Schaeffer, B. Miranda & S. Koyejo, "Are emergent abilities of large language models a mirage?," NeurIPS (2023).
  • Q. Dong et al., "A survey on in-context learning" (2022).