Few-shot prompting: which examples, in which order?
少样本提示
Enumerate demonstration orders and separate task evidence, recency effects and label bias.
few-shot-promptingThe examples stayed the same; the answer changed
Take two negative and two positive examples. Put the positive examples last, then reverse the order. A method that gives recent examples more influence can change its prediction even though the four input-output pairs are identical. “We used four examples” does not fully specify that experiment.
Few-shot prompting supplies a small set of demonstrations inside the input. In Brown and colleagues’ definition, section 2, these demonstrations do not trigger model-weight updates. The context may still consume substantial computation. Few-shot prompting is one way to set up in-context learning; the broader question of how a model adapts from context is separate from the practical choice of demonstrations.
The example here is a fixed two-class kernel classifier with an explicitly programmed recency effect. It lets us enumerate all 24 orders of four demonstrations. No language model generates the probabilities, and the recency parameter is not fitted to a paper’s measurements.
Specify pairs, order and answer vocabulary
Let the candidate answer vocabulary be a finite set. A direct classification setup selects the most likely answer conditioned on the ordered demonstrations:
A label can contain multiple tokens. Its sequence probability is a product, or equivalently a sum in log space:
Tokenization, label spelling, end-of-answer handling and any length normalization therefore belong in the evaluation specification. Comparing only the first token is not generally equivalent to comparing complete labels. Our program uses integer class IDs and bypasses tokenization; it demonstrates other effects without claiming to model this one.
Choose demonstrations that are relevant, correctly paired, available at prediction time and separate from the final evaluation set. Check whether they cover the required classes and failure cases. Four nearly identical positive examples do not provide the same information as a balanced set. Increasing the count can help, consume context or amplify a misleading pattern; count alone does not establish quality.
For the authored classifier, each scalar example gets a Gaussian similarity weight multiplied by a recency factor. Index i runs from 1 to k:
Tau controls similarity width in the input’s units. Gamma=1 removes recency weighting. Smaller gamma reduces the influence of earlier examples. This is an explicit modeling choice, not a statement that Transformer attention follows this formula.
Add a positive pseudo-count alpha times a fixed class prior pi, then normalize:
The positive prior prevents zero scores, including when no demonstrations are supplied or similarity underflows. With no examples, the output is exactly pi. With gamma=1, permuting examples leaves the mathematical sum unchanged. With gamma below 1, different classes can receive different total recency weights.
Zhao and colleagues, section 5, estimate prompt-induced label preference from content-free inputs. To illustrate the decision correction, our query=None sets every similarity to 1 while keeping recency, labels and prior. Divide query probabilities by this baseline and normalize the ratios:
All baseline components must be positive. A rare baseline label gets boosted; a bad baseline can boost the wrong answer. This operation does not prove confidence calibration. It is also important to distinguish our displayed probabilities from the paper’s formula. Zhao’s equation 1 applies softmax to scaled probabilities, while prediction takes their argmax. With zero bias and inverse-baseline diagonal scaling:
The two distributions have the same maximizing class because both transformations are monotone in r, but their numerical probabilities differ. For p=(0.6,0.4) and b=(0.8,0.2), our ratio-normalized result is(3/11,8/11). Do not present those values as the paper’s softmax probabilities.
For a fixed query set, calculate accuracy for every permutation and report its range as well as its average:
For four distinct example records, there are 24 permutations. The program resolves a class-score tie in favor of class 0 through argmax; that convention matters for a content-free or fully tied case.
Enumerate every order
The complete Python 3.12/NumPy 1.26.4 program uses negative examples at −1 and −0.7, positive examples at 0.7 and 1, and queries −1,−0.5,0.5,1. The class prior is(0.2,0.8), bandwidth 0.8 and prior pseudo-count 0.5. These constants are authored to expose the effects.
"""A fixed kernel classifier with authored recency and label priors, not an LM."""
import itertools,json,math
import numpy as np
def distribution(examples,query,gamma=1.0,bandwidth=.8,alpha=.5,prior=(.2,.8)):
for value in [gamma,bandwidth,alpha]:
if isinstance(value,bool) or not math.isfinite(value):raise ValueError('finite parameters required')
if not 0<gamma<=1 or bandwidth<=0 or alpha<=0:raise ValueError('positive scale and gamma in(0,1] required')
prior=np.asarray(prior,dtype=float)
if prior.shape!=(2,) or not np.isfinite(prior).all() or np.any(prior<=0) or not np.isclose(prior.sum(),1):raise ValueError('positive normalized binary prior required')
if query is not None and (isinstance(query,bool) or not math.isfinite(query) or abs(query)>100):raise ValueError('bounded query required')
if len(examples)>100:raise ValueError('at most100 examples')
scores=alpha*prior.copy()
for i,(x,y) in enumerate(examples):
if isinstance(x,bool) or not math.isfinite(x) or abs(x)>100 or type(y) is not int or y not in [0,1]:raise ValueError('finite scalar and binary label required')
similarity=1.0 if query is None else math.exp(-.5*((query-x)/bandwidth)**2)
scores[y]+=gamma**(len(examples)-1-i)*similarity
return scores/scores.sum()
def normalized_ratio(probability,baseline):
p=np.asarray(probability,dtype=float);b=np.asarray(baseline,dtype=float)
if p.shape!=(2,) or b.shape!=(2,) or not np.isfinite(p).all() or not np.isfinite(b).all() or np.any(p<0) or np.any(b<=0) or not np.isclose(p.sum(),1) or not np.isclose(b.sum(),1):raise ValueError('normalized binary distributions; positive baseline required')
ratio=p/b
return ratio/ratio.sum()
def accuracy(examples,queries,truth,gamma):
raw=[];corrected=[];baseline=distribution(examples,None,gamma)
for q in queries:
p=distribution(examples,q,gamma);raw.append(int(p.argmax()));corrected.append(int(normalized_ratio(p,baseline).argmax()))
return dict(raw=float(np.mean(np.array(raw)==truth)),ratio=float(np.mean(np.array(corrected)==truth)),baseline=baseline.tolist())
def demo():
examples=[(-1,0),(-.7,0),(.7,1),(1,1)];queries=np.array([-1,-.5,.5,1]);truth=(queries>0).astype(int)
permutations=list(itertools.permutations(examples));rows=[]
for g in [1.0,.5,.2]:
values=[accuracy(e,queries,truth,g) for e in permutations]
rows.append(dict(gamma=g,raw_min=min(v['raw'] for v in values),raw_max=max(v['raw'] for v in values),raw_mean=float(np.mean([v['raw'] for v in values])),ratio_min=min(v['ratio'] for v in values),ratio_max=max(v['ratio'] for v in values),ratio_mean=float(np.mean([v['ratio'] for v in values]))))
positive_only=[(.7,1),(1,1),(.8,1),(.9,1)]
comparison={name:accuracy(e,queries,truth,.5) for name,e in [('balanced',examples),('positive_only',positive_only),('flipped',[(x,1-y) for x,y in examples])]}
return dict(examples=[list(x) for x in examples],queries=queries.tolist(),truth=truth.tolist(),order_results=rows,comparison=comparison,order_count=len(permutations),zero_shot=accuracy([],queries,truth,1.0))
if __name__=='__main__':print(json.dumps(demo(),indent=2,allow_nan=False))
With gamma=1, every order scores 1.0 on these four queries. At gamma=0.5, raw accuracy ranges from 0.5 to 1.0, with mean about 0.88542. Ratio correction gives 1.0 for every order in that case. At gamma=0.2, corrected accuracy still ranges from 0.75 to 1.0: correction is not a guarantee.
comparison holds gamma at 0.5 and changes the demonstrations. The chosen balanced order has raw accuracy 0.5 and corrected accuracy 1.0. Four positive-only demonstrations yield 0.5 after correction. Flipping all labels gives 0.0 after correction. The model still depends on the input-label mapping; a bias correction cannot invent missing class evidence or repair every wrong label.
One prediction costs O(k) for scalar inputs and uses two class accumulators. Exhaustive order evaluation over Q queries costs O(k! Qk); it is feasible here because k=4. For larger prompts, predeclare a sampled set of orders or a controlled ordering strategy. Charge their evaluation cost rather than reporting the best order for free.
Interpret randomized-label results narrowly
Min and colleagues, sections 3–4, compare gold and randomized labels across classification and multiple-choice tasks. Their default uses 16 demonstrations; the largest models are evaluated on a smaller six-dataset subset. Randomizing labels often has a smaller effect than might be expected in those conditions. Their ablations also show variation across models and tasks.
That evidence does not establish that correct labels never matter, that a newly invented label mapping can always be recovered, or that demonstrations are interchangeable. Our counterexample makes the issue concrete: flipped labels destroy this classifier’s performance. The counterexample does not refute Min’s measurements; it shows why their empirical scope must be preserved.
The kernel model is permutation-invariant when gamma=1 and has only two numeric labels. A language model can respond to format, wording, semantic relationships, token frequencies and position in more complicated ways. Test new inputs, class balance, contradictory examples and domain shifts. Avoid presenting a favorable order as a universal prompt recipe.
Change one part of the demonstration
- Why does gamma=1 remove order effects in this program?
Answer: Every recency factor becomes 1, so each class score is an ordinary sum over the same examples. Reordering does not change that sum, apart from floating-point roundoff.
- Compute ratio correction for p=(0.6,0.4), b=(0.8,0.2). Is it the paper’s softmax distribution?
Answer: Ratios are 0.75 and 2, so normalization gives 3/11 and 8/11. The maximizing class matches softmax of those ratios, but the probability values differ.
- Why does checking the best of 24 orders on the final test set give a biased comparison?
Answer: The test has become a selection set. Pick the ordering rule on separate development data, freeze it, and evaluate once on untouched cases. Report the cost of evaluating candidate orders.
- Do the gold/random-label results justify deliberately corrupting all labels in an unfamiliar task?
Answer: No. They are results for specified models and task collections. Our flipped-label example scores 0.0, demonstrating that label dependence is possible. Preserve correct examples and test the actual task.
Three questions, three source locations
Brown, section 2, defines the evaluation settings. Min, sections 3–4, tests which information in demonstrations matters under stated conditions. Zhao, section 5, changes label decision scores using a content-free baseline and explicitly distinguishes that procedure from confidence calibration. Prompt-selection methodology is covered in prompt engineering; answer voting after generation is covered in self-consistency.
Make a prediction, then check
Does a result with randomized labels prove correct examples never matter?
Learning objectives
- Specify demonstrations, ordering, answer vocabulary and the cost of comparisons.
- Run the bounded original example and explain the failure cases.
Prerequisites & connections
Explore related knowledge →References
- Language Models are Few-Shot Learners — arXiv v4
Tom B. Brown; Benjamin Mann; Nick Ryder and coauthors · 2020 - Rethinking the Role of Demonstrations: What Makes In-Context Learning Work? — v1
Sewon Min; Xinxi Lyu; Ari Holtzman; Mikel Artetxe; Mike Lewis; Hannaneh Hajishirzi; Luke Zettlemoyer · 2022 - Calibrate Before Use: Improving Few-Shot Performance of Language Models — v1
Tony Z. Zhao; Eric Wallace; Shi Feng; Dan Klein; Sameer Singh · 2021
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-20 · Single AI author. New scoped reading: viewed PDF6/7 section2 and Figure2.1, read PDF3 Figure1.1 text. No task-specific gradient update; existing Source object preserved. Viewed PDF3/4:26 datasets,16 default demonstrations, reduced six-dataset evaluation for largest models, gold/random labels and ablations. Not a claim that labels never matter. Viewed PDF5 section5 and footnotes: content-free inputs, diagonal probability scaling, softmax versus argmax, and distinction from confidence calibration. Do not implement the suspect zero-W generation footnote. 7 paired equations and four explained exercises. All24 orders, prior and recency counts, ratio/softmax rank versus probability distinction, wrong labels and incomplete class evidence checked. Empirical paper scope preserved.
- All24 orders, prior and recency counts, ratio/softmax rank versus probability distinction, wrong labels and incomplete class evidence checked. Empirical paper scope preserved.
- 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:
- Language Models are Few-Shot Learners — arXiv v4 · New scoped reading: viewed PDF6/7 section2 and Figure2.1, read PDF3 Figure1.1 text. No task-specific gradient update; existing Source object preserved.
- Rethinking the Role of Demonstrations: What Makes In-Context Learning Work? — v1 · Viewed PDF3/4:26 datasets,16 default demonstrations, reduced six-dataset evaluation for largest models, gold/random labels and ablations. Not a claim that labels never matter.
- Calibrate Before Use: Improving Few-Shot Performance of Language Models — v1 · Viewed PDF5 section5 and footnotes: content-free inputs, diagonal probability scaling, softmax versus argmax, and distinction from confidence calibration. Do not implement the suspect zero-W generation footnote.
Related topics