AI Wiki中文/EN

In-context learning: change the examples, keep the model fixed

上下文学习

Infer a finite hidden task and see why repeated examples need not resolve uncertainty.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Two examples can reveal more than twenty copies

A clearly specified toy task hides a rule of the form “multiply by a number, then add another number.” You see 0 → 1. That tells you the offset, but nothing about the multiplier. Repeating the same pair twenty times does not answer what happens at 2. Seeing 1 → 3 instead can settle the question, provided the true rule belongs to the candidate family.

In-context learning changes a model’s behavior through the context supplied at inference time. In the setup studied by Brown and colleagues, section 2, examples appear in the input sequence; the model does not take task-specific gradient updates. Its activations and generated answer change, even though its learned parameters stay fixed. This distinguishes context from fine-tuning; it does not imply that the model has learned nothing during its earlier training.

Garg and colleagues, sections 2–3, train Transformers from scratch on numerical function tasks. A prompt contains examples of one sampled function and a query; the network learns across many such prompts before evaluation. That is evidence about a controlled task distribution, not a proof that every language model internally runs the same algorithm.

The program below uses an explicit Bayesian estimator over 15 rules. It gives a transparent example of task inference with a fixed mechanism. It is not a Transformer or a reproduction of either paper.

A duplicate noiseless example leaves the same five tasks possible.
A duplicate noiseless example leaves the same five tasks possible.

Keep model parameters and task uncertainty separate

Write the context as an ordered list of input-output pairs. An autoregressive model conditions its answer on both the context and the new input:

pθ(y∣D,x∗),D=((x1,y1),…,(xk,yk)),θafter=θbefore.p_\theta(y\mid D,x_*),\qquad D=((x_1,y_1),\ldots,(x_k,y_k)),\qquad \theta_{\mathrm{after}}=\theta_{\mathrm{before}}.

The equality refers to stored model parameters during this inference call. Hidden states, attention weights for the current input and the context itself can change. “No parameter update” does not mean “no computation,” “no cost,” or “permanent learning.” A later request without these examples need not retain the same behavior.

For our finite estimator, introduce a hidden task identity h. Assume one task generated every pair, a fixed prior over tasks, and conditionally independent observation errors. Bayes’ rule gives:

P(h∣D)=P(h)∏i=1kP(yi∣xi,h)∑g∈HP(g)∏i=1kP(yi∣xi,g).P(h\mid D)=\frac{P(h)\prod_{i=1}^{k}P(y_i\mid x_i,h)}{\sum_{g\in\mathcal H}P(g)\prod_{i=1}^{k}P(y_i\mid x_i,g)}.

This is an authored explanatory model. It is one possible mechanism for conditioning on examples, not an asserted description of all neural in-context learning. The denominator must be positive. If noiseless observations contradict every candidate, the model cannot explain the context and must report that failure.

Here the candidate family is small enough to enumerate:

H={ha,b(x)=ax+b:a∈{−2,−1,0,1,2}, b∈{−1,0,1}},P(h)=115.\mathcal H=\{h_{a,b}(x)=ax+b:a\in\{-2,-1,0,1,2\},\ b\in\{-1,0,1\}\},\qquad P(h)=\frac1{15}.

The hypotheses and prior are fixed. Context changes their posterior weights, not their slopes or offsets. For noiseless observations, incompatible rules receive zero mass. For independent Gaussian noise with known standard deviation sigma, all finite rules can retain likelihood:

P(yi∣xi,h)∝{1[yi=h(xi)],σ=0,exp⁡ ⁣(−(yi−h(xi))22σ2),σ>0.P(y_i\mid x_i,h)\propto\begin{cases}\mathbf 1[y_i=h(x_i)],&\sigma=0,\\\exp\!\left(-\frac{(y_i-h(x_i))^2}{2\sigma^2}\right),&\sigma>0.\end{cases}

The Gaussian normalization is the same for every rule and cancels in the posterior. The implementation subtracts the largest log likelihood before exponentiation to avoid unnecessary underflow. Its supported positive sigma range is 1e-6 through 10; zero selects the noiseless branch. These are numerical limits of the example.

Use the posterior to average candidate predictions and measure remaining task uncertainty:

μ∗=∑hP(h∣D)h(x∗),V∗=∑hP(h∣D)(h(x∗)−μ∗)2.\mu_* =\sum_h P(h\mid D)h(x_*),\qquad V_* =\sum_h P(h\mid D)(h(x_*)-\mu_*)^2.

With no examples and a query at 2, the mean is 0 up to floating-point rounding and the variance is 26/3. After 0 → 1, five slopes remain; their predictions at 2 are −3,−1,1,3,5. The mean becomes 1 and the variance 8. A duplicate pair leaves both unchanged. Adding 1 → 3 identifies 2x+1, giving 5 with zero task variance.

Why average? Under squared loss, any estimate c has the following posterior risk. If the queried observation also contains independent zero-mean noise of variance sigma squared, add that observation noise to the task variance:

E[(Y∗−c)2∣D]=V∗+(μ∗−c)2,Var⁡(Y∗+ϵ∣D)=V∗+σ2.\mathbb E[(Y_*-c)^2\mid D]=V_*+(\mu_*-c)^2,\qquad \operatorname{Var}(Y_*+\epsilon\mid D)=V_*+\sigma^2.

Expand the square around the posterior mean. The cross term vanishes because the mean residual is zero. This proves the mean minimizes posterior squared error under the stated model. It does not certify that the task family or noise assumptions match reality.

Garg’s setup has a different, outer training step. A model is optimized over sampled tasks and prompt prefixes:

min⁡θ Eh,D ⁣[1k+1∑i=0kℓ(Mθ(Di,xi+1),h(xi+1))].\min_\theta\ \mathbb E_{h,D}\!\left[\frac1{k+1}\sum_{i=0}^{k}\ell\big(M_\theta(D_i,x_{i+1}),h(x_{i+1})\big)\right].

Here D_i contains only the first i examples. The future answer is a training target, not part of that prefix. After this training, weights remain fixed while the model predicts a new task. Their paper uses learned Transformer representations; our program directly enumerates hypotheses and performs no outer training.

Run task inference without a language model

Run this complete program with Python 3.12 and NumPy 1.26.4. Inputs are at most 100 finite pairs with coordinates bounded in absolute value by 100. A hypothesis is an affine rule; the program does not discover new rule forms. The returned posterior follows the order of HYPOTHESES.

"""Finite Bayesian task inference; no Transformer training or weight update."""
import itertools,json,math
import numpy as np

HYPOTHESES=tuple(itertools.product(range(-2,3),range(-1,2)))

def infer(context,query,sigma=0.0):
    if isinstance(query,bool) or not np.isscalar(query) or not math.isfinite(query) or abs(query)>100:
        raise ValueError('query must be a finite scalar within100')
    if isinstance(sigma,bool) or not np.isscalar(sigma) or not math.isfinite(sigma) or not (sigma==0 or 1e-6<=sigma<=10):
        raise ValueError('sigma must be0 or in[1e-6,10]')
    pairs=np.asarray(context,dtype=float)
    if pairs.size==0:pairs=np.empty((0,2))
    if pairs.ndim!=2 or pairs.shape[1]!=2 or len(pairs)>100 or not np.isfinite(pairs).all() or np.max(np.abs(pairs),initial=0)>100:
        raise ValueError('bounded finite input-output pairs required')
    h=np.array(HYPOTHESES,dtype=float);errors=pairs[:,1,None]-(pairs[:,0,None]*h[:,0]+h[:,1])
    if sigma==0:
        mass=np.all(errors==0,axis=0).astype(float)
        if mass.sum()==0:raise ValueError('context has zero probability in the noiseless task family')
    else:
        logs=-np.sum((errors/sigma)**2,axis=0)/2
        mass=np.exp(logs-logs.max())
    posterior=mass/mass.sum();values=h[:,0]*query+h[:,1]
    mean=float(posterior@values);variance=float(posterior@((values-mean)**2))
    return dict(posterior=posterior.tolist(),mean=mean,task_variance=variance,predictive_variance=variance+sigma*sigma,support=int(np.count_nonzero(posterior)))

def demo():
    contexts=[[],[[0,1]],[[0,1],[0,1]],[[0,1],[1,3]]]
    results=[infer(c,2) for c in contexts]
    curve=[dict(query=q,**{k:v for k,v in infer([[0,1]],q).items() if k!='posterior'}) for q in [-2,-1,0,1,2]]
    return dict(hypotheses=[list(h) for h in HYPOTHESES],contexts=contexts,prefix_results=results,ambiguity_curve=curve,noisy=infer([[0,1],[1,2.8]],2,.5),fixed_family_unchanged=len(HYPOTHESES)==15)

if __name__=='__main__':print(json.dumps(demo(),indent=2,allow_nan=False))

The four prefix_results expose the no-context, one-example, duplicate-example and identifying-example cases. ambiguity_curve moves the query while leaving the context fixed: all surviving tasks agree at 0 and disagree away from 0. noisy shows the different positive-noise model; repeated noisy measurements would count as additional independent evidence under that assumption.

For H hypotheses and k scalar examples, the batch calculation costs O(Hk) arithmetic and stores an H-by-k residual array. A streaming implementation could use O(H) working memory. There is no language-model prefill, tokenization or learned attention here. A least-squares baseline is useful for larger linear families, but it carries different assumptions about admissible functions and noise.

A confident answer can come from a wrong family

A finite posterior only considers the rules supplied to it. A nonlinear true rule can agree on observed points and disagree at the query. Zero posterior variance then means agreement within this model, not truth. Our noiseless procedure is order-invariant; real autoregressive prompts can be sensitive to order and position. The few-shot prompting article examines that issue separately.

Task recognition, retrieval of learned associations and induction of a new input-output mapping are different explanations for successful examples. This program demonstrates the last idea within an explicit finite family. It cannot decide which explanation accounts for a particular neural model. Measure performance on new queries and new tasks, state the training distribution, and compare against a non-neural baseline before attributing a mechanism.

Predict before running

  1. After observing only 0 → 1, what does the estimator predict at 2, and why is it not necessarily 5?

Answer: It predicts the mean 1 with task variance 8. Five equally weighted slopes remain. The rule 2x+1 is only one of them.

  1. Which is more informative in the noiseless example: another 0 → 1, or 1 → 3?

Answer: The new input is informative. A duplicate rejects no additional hypothesis; 1 → 3 leaves only slope 2 with offset 1. This conclusion changes if repeated observations have independent noise.

  1. Why does 0 → 1 followed by 0 → 0 raise an error when sigma is zero?

Answer: No deterministic rule can satisfy both observations. The posterior denominator is zero. Quietly returning a uniform posterior would conceal a model-data contradiction.

  1. Does the program establish that Transformers implement Bayesian inference?

Answer: No. It establishes the behavior of this explicit estimator. A claim about a Transformer requires evidence about that trained model and competing explanations; matching a few predictions is insufficient.

Read the setup before the conclusion

Brown, section 2 and Figure 2.1, distinguishes zero-shot, one-shot, few-shot and fine-tuning evaluation. Garg, sections 2–3, specifies the task distribution, prefix training objective and baselines for a numerical study. The latter is trained from scratch on numerical prompts, not obtained by asking a general chat model a few arithmetic questions. Continue to instruction tuning for changing parameters and to few-shot prompting for choosing demonstrations.

Make a prediction, then check

Do repeated examples at the same input identify every possible task?

Choose one answer

Learning objectives

  • Distinguish inference-time conditioning from learned parameters and task identification.
  • Run the bounded original example and explain the failure cases.

Prerequisites & connections

Explore related knowledge →

References

  1. What Can Transformers Learn In-Context? A Case Study of Simple Function Classes — v1
    Shivam Garg; Dimitris Tsipras; Percy Liang; Gregory Valiant · 2022
  2. Language Models are Few-Shot Learners — arXiv v4
    Tom B. Brown; Benjamin Mann; Nick Ryder and coauthors · 2020

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-20 · Single AI author. Viewed PDF3/4 sections2/3: function-task sampling, prefix loss, from-scratch numerical Transformer training and least-squares baseline. No neural model reproduced. New scoped reading: viewed PDF6/7 section2 and Figure2.1, read PDF3 Figure1.1 text. No task-specific gradient update; existing Source object preserved. 7 paired equations and four explained exercises. Finite15-task posterior, ambiguity, repeated noiseless examples, identification, squared-risk identity and likelihood ratios checked. No Transformer mechanism or neural reproduction claim.

  • Finite15-task posterior, ambiguity, repeated noiseless examples, identification, squared-risk identity and likelihood ratios checked. No Transformer mechanism or neural reproduction claim.
  • Four computed SVG variants per topic;9 numeric/geometry tests and24 responsive cases passed. Eight selected final captures directly viewed. Full article acceptance recorded separately.
  • Final page inspection found missing spaces at English prose number boundaries. Inserted only the explicitly recorded spaces; protected formulas, code, inline literals, links and frontmatter unchanged. Frozen originals retained; exact insertion regression and renewed page checks required.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.