Level 0: Foundation
★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.How can a model learn without changing?
A language model’s weights stay fixed while it reads a prompt, yet it can pick up a new task from a few examples. One explanation: during training it saw so many kinds of text that it learned to work out which kind it is reading now. Another: its layers have learned to run a small learning procedure, like a few steps of fitting a line, every time they read examples. A third looks at specific circuits that copy patterns. The demo shows the first view: examples narrow down which task is meant.
Knowing what in-context learning can and cannot do (it is limited by pretraining and by the depth of the model) helps decide when prompting suffices and when fine-tuning is needed.
- 1. During in-context learning the weights…
- 2. A linear attention layer can implement…
- 3. Induction heads…
Level 1: Beginner
★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.By hand
- Bayesian view (Xie et al., 2022): prompts are evidence about a latent concept; predictions average over the posterior.
- Algorithmic view (Garg et al., 2022; Akyürek et al., 2023; von Oswald et al., 2023): Transformers trained on in-context linear regression match least squares or ridge; constructions show attention layers implementing gradient-descent steps; a linear self-attention layer computes x_qᵀ Γ (1/n) Σ yᵢ xᵢ, one GD step from zero when Γ = ηI.
- Mechanistic view (Olsson et al., 2022): induction heads (a previous-token head plus a head that attends to the token after the earlier match) form during a phase change in training that coincides with a jump in in-context learning.
- Data view (Chan et al., 2022): in-context learning emerges when training data is ‘bursty’ and has many rare classes.
- Limits: depth bounds the number of algorithmic steps; the learned algorithm is tuned to the training distribution (context lengths, task priors); real LLMs mix retrieval of known tasks and genuine learning.
- 1. Linear attention with Γ = ηI computes…
- 2. Induction heads appear…
- 3. In-context learning emerges more with data that is…
Level 2: Intermediate
★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.Probing in-context learning
Exercise 1.
- Compute the linear self-attention prediction.
- Compute the one-step gradient-descent prediction and check they match for Γ = ηI.
- Implement softmax attention for comparison.
Practice.
- Synthetic in-context tasks (linear regression, Markov chains, associative recall) are the standard testbeds; train small Transformers in PyTorch and compare with known algorithms.
- TransformerLens can locate induction heads in real models by their attention patterns on repeated random sequences.
- Practical takeaway: in-context learning is strongest for tasks and context lengths like those seen in training; for novel tasks, measure before relying on it.
import torch
from transformer_lens import HookedTransformer
model = HookedTransformer.from_pretrained("gpt2-small")
seq = torch.randint(1000, 10000, (1, 50)); tokens = torch.cat([seq, seq], dim=1) # repeated random tokens
_, cache = model.run_with_cache(tokens)
# induction score: attention from position i to position i - 49 (the token after the earlier copy)
scores = {(l, h): cache["pattern", l][0, h].diagonal(-49).mean().item() for l in range(12) for h in range(12)}- 1. A library for finding induction heads:
- 2. Induction heads are found with…
- 3. Standard synthetic ICL testbed:
Level 3: Advanced
★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.Theory
Linear attention is one GD step. For loss L(w) = (1/2n) Σ (w·xᵢ − yᵢ)², the gradient at w = 0 is −(1/n) Σ yᵢ xᵢ. One step gives w₁ = η (1/n) Σ yᵢ xᵢ and prediction x_qᵀ w₁. A linear self-attention layer with keys xᵢ, values yᵢ and query x_q outputs x_qᵀ Γ (1/n) Σ yᵢ xᵢ, the same with Γ = ηI. A general Γ is a preconditioned step.
What training finds. Meta-training Γ minimises the expected query error over the task distribution. For isotropic tasks the optimum is Γ = ηI with η = n/(n + d + 1), the best single step. For tasks in a subspace, the optimal preconditioner is a scaled projection onto that subspace: the layer has learned the prior, which is the bridge to the Bayesian view.
Limits. One step of GD is far from least squares unless n ≫ d; deeper stacks can emulate more steps (or other algorithms), and trained Transformers approach ridge regression. A learned step size is tuned to the training context length, so behaviour changes with longer prompts.
- 1. The best single GD step size for isotropic tasks:
- 2. A subspace task prior leads the layer to learn…
- 3. More layers can emulate…
Level 4: Expert
★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.What algorithm does a trained linear attention layer implement, and does it adapt to the task prior?
History.
- S. Garg, D. Tsipras, P. Liang and G. Valiant, “What can Transformers learn in-context?” (NeurIPS 2022).
- C. Olsson et al., “In-context learning and induction heads” (2022).
- E. Akyürek et al., “What learning algorithm is in-context learning?” (ICLR 2023).
- J. von Oswald et al., “Transformers learn in-context by gradient descent” (ICML 2023).
Exercise 2.
- Tasks: linear regression in 5 dimensions, 10 context examples, noise 0.1, task weights N(0, I).
- Training: Γ of a linear self-attention layer trained by SGD on freshly sampled tasks (3000 steps of 256).
- Comparisons (20 000 test tasks): one GD step with the best step size; ridge regression (essentially the Bayes-optimal learner); predicting zero. Then the same with longer contexts (40 examples), and with task weights confined to a random 2-D subspace.
| test MSE, n = 10 | test MSE, n = 40 | |
|---|---|---|
| predict zero | 4.907 | 5.000 |
| trained linear attention | 1.873 | 1.025 |
| one GD step, best step size | 1.850 | 0.662 |
| ridge regression | 0.022 | 0.011 |
| subspace task prior | test MSE |
|---|---|
| linear attention trained on isotropic tasks | 0.769 |
| one GD step, best step size | 0.749 |
| linear attention trained on subspace tasks | 0.462 |
- The layer learned gradient descent: Γ was nearly diagonal (off-diagonal entries ≤ 0.044) with mean diagonal 0.624, the theoretical optimal step 10/16 = 0.625, and its error matched tuned one-step GD.
- One step is a weak learner: ridge regression was 85× better. A single attention layer cannot do what a deep model or an explicit solver can.
- No adaptation to context length: at 40 examples its fixed step was too small (1.03 against 0.66 for a re-tuned step).
- It learned the prior: trained on subspace tasks, Γ had two eigenvalues near 0.78 and three near 0, a projection, and beat plain GD by 38%.
- Seeds 1 and 2: same pattern (diagonal means 0.58 and 0.63; subspace 0.47 against 0.77 and 0.75).
ICL theory in AI, robotics and aerospace
- Model selection: knowing that in-context learning is tuned to the pretraining distribution explains why it fails on unfamiliar domain formats.
- In-context adaptation in control: Transformers trained across many systems adapt to a new system from its recent trajectory, a form of in-context system identification.
- Interpretability: induction-head and algorithmic analyses are early steps towards verifying what a model computes.
References
- J. von Oswald et al. (2023). “Transformers learn in-context by gradient descent.” ICML.
- S. Garg, D. Tsipras, P. Liang and G. Valiant (2022). “What can Transformers learn in-context? A case study of simple function classes.” NeurIPS.
- C. Olsson et al. (2022). “In-context learning and induction heads.” Transformer Circuits Thread.
- E. Akyürek, D. Schuurmans, J. Andreas, T. Ma and D. Zhou (2023). “What learning algorithm is in-context learning? Investigations with linear models.” ICLR.