Worked examples — In-context learning mechanisms
This page is the practice arena for the parent note. There we built the Bayesian task-inference view (demos shift a posterior over hidden tasks) and the attention-as-one-gradient-step view. Here we run those two engines on every case class ICL can throw at you — and we compute real numbers so you can feel the machinery move.
Before we start, a one-line refresher of the two symbols we will reuse constantly:
Recall What do
, , and mean? is a hidden "task" the model could be doing (e.g. "classify sentiment"). is the ==bag of demonstrations== you put in the prompt. is the model's ==belief that task is the one you want==, after reading those demos. -shot ::: a prompt carrying demonstrations before the query ( means zero examples).
We also need one measurement that keeps returning throughout this page: how far apart two tasks are.
The scenario matrix
Every ICL question you will ever see lands in one of these cells. Each worked example below is tagged with the cell(s) it covers.
| Cell | Case class | What breaks / what to watch | Covered by |
|---|---|---|---|
| C1 | (zero-shot), degenerate | no demos → posterior = prior only | Ex 1 |
| C2 | growing, clean demos | posterior collapses exponentially in | Ex 2 |
| C3 | Saturation / limiting | diminishing returns, formal plateau | Ex 2, Ex 3, Ex 9 |
| C4 | Two tasks nearly identical (small KL) | slow collapse — needs many shots | Ex 3 |
| C5 | Wrong / flipped labels | format survives, mapping degrades | Ex 4 |
| C6 | Ordering & recency bias | reordering flips the answer | Ex 5 |
| C7 | Attention = one GD step (numeric) | dot-product prediction sign & size | Ex 6 |
| C8 | Real-world word problem | choosing shot count under a budget | Ex 7 |
| C9 | Exam twist / limiting degenerate | two indistinguishable tasks, KL | Ex 8 |
| C10 | Unequal priors () | prior helps or fights the evidence | Ex 10 |
We will use one running toy world so numbers are comparable across examples.
Example 1 — Zero-shot: the degenerate case (C1)
Forecast: guess before reading — with zero evidence, is the model sure, unsure, or biased?
- Write the posterior with . The product over zero demos is empty, so it equals . Why this step? An empty product is by definition — "multiply nothing" changes nothing. This forces the formula to fall back on the prior only.
- Plug in. Why this step? With no evidence, Bayes returns the prior untouched.
Answer: — a coin-flip. The model is maximally unsure between the two tasks and relies entirely on whatever the pretraining prior favours.
Verify: Symmetric priors, no data ⇒ posterior must equal prior . Units are a probability in . ✓
Example 2 — Clean demos, growing : watch the collapse (C2, C3)
Forecast: does the belief rise linearly, jump then plateau, or fall?
- Per-demo likelihood ratio. Why this step? Because priors are equal, the posterior depends only on the accumulated ratio — this is the compact form of Step 1.
- Posterior formula in terms of . With equal priors, Why this step? Divide top and bottom of the two-task posterior by ; every factor collapses into .
- Evaluate.
- Why this step? Just powers of over "power ".
Answer: belief climbs — big early jumps, then saturation toward .

Verify: The parent claims grows . Here , a straight line in (yellow line in the figure) — exactly linear log-odds, exponential collapse of the complement. ✓
Example 3 — Nearly identical tasks: slow collapse (C3, C4)
Forecast: more shots or fewer shots than Example 2?
- Ratio. Why this step? Small gap ⇒ close to ⇒ weak evidence per demo.
- Solve . This means , i.e. Why this step? ; take logs to isolate .
- Round up. shots. Why this step? must be a whole number of demos, and we need to exceed the threshold, so ceil.
Answer: 11 shots — versus only 4 shots for the same target in Example 2 (; check: gives , gives , so the minimum is ).
Verify: ✓, and ✓ so 11 is the true minimum. The small-KL cell C4 genuinely needs many more demos — this is why "hard/novel" tasks demand more shots.
Example 4 — Flipped labels: format survives, mapping degrades (C5)
Forecast: does flipping labels destroy task location, mapping, both, or neither?
- Task-identity posterior. Uses : Why this step? Format/label-space/input-distribution survive label flips — flipping a label doesn't change that it looks like the task.
- Mapping posterior. Uses : Why this step? With equal-and-opposite label evidence, the ratio product is ; the mapping belief stays at the prior.
Answer: task identity (strong), correct mapping (coin-flip). The model still knows what game it's playing but must fall back on its pretraining prior for the actual answer.
Verify: matches the parent's Example 2 claim exactly — "labels don't matter" for task location, but mapping collapses to prior, so on novel tasks (weak prior) accuracy tanks. Probabilities in ✓. See Fine-tuning vs Prompting for why weight updates would fix the mapping.
Example 5 — Ordering & recency bias (C6)
Forecast: does the model answer 2 (the true match for B) or something recency-driven?
- Set the content-match scores from the rule above. Query key is
B. The demoB→2is an exact key match → content . SupposeCis a lexical near-miss toB(adjacent letter / similar embedding) → partial match → content .Ais neither → content . Why this step? We must state where every number comes from: content is our declared match rule (exact / partial / none), not a magic constant. Real heads learn a graded similarity; we discretise it to three levels so the arithmetic is transparent. - Distances from the query (query is position 4).
C→3is distance 1,B→2distance 2,A→1distance 3, so . Why this step? Recency bias means the nearest demo tokens dominate the residual stream. - Score = content × recency. ; ; . Why this step? Combine the two declared factors; the thin gap vs is exactly what makes ICL fragile.
Answer: predicts 2 (score ), but the margin over the recency lure C→3 is only .
Reorder test: put C→3 last (distance 1) and B→2 far back (distance 3): now and . Now 3 wins — the answer flipped purely from ordering.
Verify: , , ; before-reorder max is B (), after-reorder max is C (). Different winners ✓ — a clean demonstration of cell C6.
Example 6 — Attention is one gradient step: a full numeric run (C7)
Recall The parent result we are using (linear-attention ↔ one GD step)
Fit a linear model to demos with squared-error loss, starting from . One gradient-descent step with step size gives , so its prediction on a query is . A single linear attention head that uses , , and dot-product similarity outputs — the identical formula. So the forward pass "trains" a virtual linear model in its activations.
Forecast: will be positive, negative, or zero?
- Dot products. . Why this step? The dot product is the "similarity" the attention head uses to weight each value.
- Weighted sum of values. Why this step? , so we add each label times its similarity — exactly .
- Cross-check via the GD weight matrix — mind the shapes. Here each is a column and each label is a scalar (), so the outer product is (scalar)( row) a row. Summing two rows keeps a row: Then — a times a gives the scalar prediction, dimensions matching a single-output linear model . This is the same operator the attention read-out applies (values against keys ), which is why the two routes must agree. Why this step? Checking shapes proves is the correct orientation: it maps an input column to a scalar output, exactly like the attention head that reads keys and emits value-weighted scalars.

Answer: . The forward pass literally computed one Gradient Descent step's prediction — no weights of the real network moved.
Verify: both routes yield ✓; sign is negative because the query leans toward (dot ), whose label is .
Example 7 — Real-world word problem: budget your shots (C8)
Forecast: will the final demo add a lot or a little?
- Max demos in budget. demos. Why this step? Integer division — you cannot use a partial demo.
- Accuracy at . Why this step? Plug into the collapse law .
- Marginal gain of demo 5. Why this step? Cost–benefit: 60 tokens bought only percentage points — the saturation warned about in cell C3.
Answer: fit 5 demos, reach 96.97%, but the 5th demo adds only ~2.85 points for 60 tokens.
Verify: , , difference ✓. Consistent with the parent mistake "more shots always help" being false. For a permanent fix you'd choose fine-tuning or add retrieval instead of stuffing demos.
Example 8 — Exam twist: two indistinguishable tasks, (C9)
Forecast: will more demos ever help here?
- Per-demo ratio. for all demos. Why this step? Identical likelihoods ⇒ no evidence to prefer either task.
- Posterior for any . — frozen at the prior forever. Why this step? regardless of ; the limit as is still .
- KL per demo. Why this step? When two distributions are equal, KL is exactly zero — the parent's "collapse rate " gives zero collapse.
Answer: for all ; the limit is ; . No number of demos can disambiguate tasks that pretraining made identical. This is the degenerate limit of cell C9 — and it explains why some tasks are simply unreachable by ICL and need different scaffolding or new weights.
Verify: posterior for ✓; KL of a distribution with itself is ✓ (link to Bayesian Inference).
Example 9 — The formal limit : proving the plateau (C3)
Forecast: does the belief reach exactly , approach forever, or level off below ?
- Rewrite the posterior by dividing by . Why this step? Isolating exposes the only term that depends on ; everything else is constant.
- Take the limit. As with , , so Why this step? means is a shrinking geometric sequence; its limit is . So the belief approaches but never equals it for finite — an asymptote.
- Quantify the error. For this is : the error at least halves every demo. Why this step? "Geometric decay of the error" is the precise meaning of exponential collapse — and dividing by ever-larger is why gains shrink as grows (the plateau).
Answer: , approached with error (for : err , e.g. the true ). The curve saturates at from below — never touching it, gains shrinking geometrically. This is the formal content of cell C3.
Verify: at , true error , and the bound ✓; limit is ✓.
Example 10 — Unequal priors: when pretraining helps or fights (C10)
Forecast: will the demos still win, and will it take more or fewer shots than the equal-prior case?
- General posterior with priors. Divide top and bottom by : Why this step? The prior-odds multiplies the evidence, so a bad prior is a handicap the demos must overcome — this generalises the equal-prior formula (recover it by setting ).
- (a) Zero-shot (). Why this step? With no demos the belief is the prior — the model starts out believing the wrong task.
- (b) Overturn the prior. Need , i.e. , i.e. , so . Why this step? ; the demos must supply likelihood-odds big enough to cancel the prior-odds .
- Sanity at . exactly; at , . Why this step? Confirms is the crossover and the belief keeps climbing after.
Answer: (a) zero-shot ; (b) need demos just to reach the coin-flip , and more to be confident; (c) posterior . A hostile prior costs extra shots; a favourable prior (large ) would let fewer demos — or even zero — suffice. This is cell C10, and it explains why the same demos work instantly on tasks the model already expects, but sluggishly on tasks its pretraining resists.
Verify: ✓; so crossover, with belief exactly ✓ and at ✓.
Recall Quick self-test
With equal priors and per-demo ratio , what is ? ::: . Write the KL divergence between the true and rival task. ::: , always , zero iff the two distributions are identical. Why does the KL case never improve? ::: Every per-demo likelihood ratio is , so the posterior stays pinned at the prior no matter how many demos you add. With prior , what is the posterior after demos (ratio )? ::: . In Ex 6, why is the ICL prediction negative? ::: The query is more similar (larger dot product, ) to the demo whose label is . How would the two-task analysis change for classes? ::: It becomes a softmax over all tasks; collapse speed is set by the closest competitor (smallest pairwise KL), so it is never easier than the hardest pair.
Practice done. Return to the parent and re-read the two mechanistic stories — every cell above is one of those two engines run to its edge.