AI Wiki中文/EN

GPT: pretraining, adaptation and examples in context

GPT 架构与预训练

Follow the original GPT training objective and distinguish parameter updates from fixed-model conditioning.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

The same example can enter in two different places

Give a model examples of a new labeling rule. You can use those examples to calculate gradients and update its parameters. Or you can place them in its input and ask the unchanged model for a continuation. Both procedures use examples, but they change different things. Confusing them obscures the development from the original GPT training recipe to GPT-3’s evaluation of demonstrations in context.

The 2018 GPT report first trains a language model on unlabeled text, then adapts it to supervised tasks. It uses a Transformer decoder and task-specific input transformations, with an added prediction layer for the supervised task. GPT-2’s report develops task conditioning through text sequences. GPT-3 explicitly distinguishes fine-tuning, zero-shot, one-shot and few-shot settings; its few-shot evaluation supplies demonstrations during inference without updating model weights. Original GPT GPT-2 GPT-3

This chapter follows those objectives and interfaces. The decoder architecture explains the causal stack itself. The small program below compares a real parameter update with exact Bayesian conditioning over two fixed rules. It does not claim that GPT implements that Bayesian calculation internally.

Parameter updates and conditioning change different objects; the two toy mechanisms are not a performance comparison.
Parameter updates and conditioning change different objects; the two toy mechanisms are not a performance comparison.

A language-model objective, then an adaptation objective

For a token sequence u1,…,uNu_1,\ldots,u_N, a context limit kk and parameters θ\theta, the original report maximizes an autoregressive log-likelihood. Written as a negative objective to minimize:

LLM(θ)=−∑i=1Nlog⁡pθ(ui∣umax⁡(1,i−k):i−1). \mathcal L_{\mathrm{LM}}(\theta)=-\sum_{i=1}^{N}\log p_\theta(u_i\mid u_{\max(1,i-k):i-1}).

The start of a sequence needs a boundary convention. Attention masking alone does not specify how targets are shifted or how documents are separated. Those data-processing choices belong to the training setup. The original GPT report uses a multi-layer Transformer decoder, learned positional embeddings and contiguous text sequences; “Transformer” does not imply that the position embeddings must be sinusoidal. Original GPT, sections 3.1 and 4.1

For supervised adaptation, let hθ(x)h_\theta(x) be the representation selected from the task-formatted input, WW the new classifier parameters and yy the label. A softmax head gives:

pθ,W(y∣x)=softmax⁡ ⁣(hθ(x)W)y. p_{\theta,W}(y\mid x)=\operatorname{softmax}\!\left(h_\theta(x)W\right)_y.

The original report also includes an auxiliary language-model term during fine-tuning. In the same minimizing sign convention, the combined objective is:

Ladapt=Lsup+λLLM. \mathcal L_{\mathrm{adapt}}=\mathcal L_{\mathrm{sup}}+\lambda\mathcal L_{\mathrm{LM}}.

Its paper writes log-likelihoods to maximize; changing signs consistently produces the expression above. The auxiliary weight is an experimental choice, not a definition of every later GPT system. Task formatting matters too: sentence-pair similarity, entailment and multiple-choice questions require different sequences or pooling arrangements. Original GPT, sections 3.2–3.3

A gradient step changes persistent parameters. Conditioning supplies different inputs to parameters that stay fixed:

θ′=θ−η∇θL(D;θ),pθ(y∣D,x) uses unchanged θ. \theta'=\theta-\eta\nabla_\theta\mathcal L(D;\theta), \qquad p_\theta(y\mid D,x)\ \text{uses unchanged }\theta.

The second expression does not say that the computation is unchanged. Activations, attention patterns and predictions can differ when DD changes. It says that the stored model weights are not updated by that inference procedure. GPT-3’s few-shot definition uses this distinction; the supplied demonstrations are not a claim that the model received gradient-based fine-tuning on that task. GPT-3, section 2

For an inspectable analogy, consider two binary labeling rules: identity and inversion. Both have prior probability one-half. Each rule gives its intended label with probability 0.9 and the other label with probability 0.1. Given demonstrations DD, exact conditioning gives:

p(r∣D)=p(r)∏(x,y)∈Dp(y∣x,r)∑r′p(r′)∏(x,y)∈Dp(y∣x,r′). p(r\mid D)=\frac{p(r)\prod_{(x,y)\in D}p(y\mid x,r)}{\sum_{r'}p(r')\prod_{(x,y)\in D}p(y\mid x,r')}.

After examples (0,1) and (1,0), inversion has posterior probability 81/8281/82. Predicting label one for query zero averages the two rules:

p(y=1∣x=0,D)=∑rp(y=1∣x=0,r)p(r∣D)=0.1+0.88182≈0.890244. p(y=1\mid x=0,D)=\sum_r p(y=1\mid x=0,r)p(r\mid D) =0.1+0.8\frac{81}{82}\approx0.890244.

No rule parameter was optimized. Only the posterior used for this query changed. This exact, order-invariant example is simpler than a language model and deliberately cannot support claims about GPT’s actual internal learning algorithm.

Compare a changed weight with a changed context

The original NumPy program also fits a one-parameter logistic model. Inputs are minus one and plus one; their target probabilities are 0.1 and 0.9. After pretraining, the weight is close to log⁡9\log9. Switching to inverted targets and fine-tuning drives it toward −log⁡9-\log9. These are deterministic soft-target objectives, so there is no sampling noise in the reported losses.

"""One-parameter fine-tuning versus fixed two-rule Bayesian conditioning."""
import json
import numpy as np


def loss_grad(weight, inverted=False):
    x=np.array([-1.,1.]);target=np.array([.1,.9])
    if inverted:target=1-target
    z=weight*x;p=np.exp(-np.logaddexp(0,-z))
    return float(np.mean(np.logaddexp(0,z)-target*z)),float(np.mean((p-target)*x))


def train(weight, inverted=False, steps=300):
    if steps<0 or not np.isfinite(weight):raise ValueError('Invalid training input')
    trace=[]
    for step in range(steps+1):
        loss,grad=loss_grad(weight,inverted)
        if step%50==0:trace.append([step,loss,float(weight)])
        if step<steps:weight-=.5*grad
    return float(weight),trace


def condition(examples, query, noise=.1):
    if query not in (0,1) or not 0<noise<.5:raise ValueError('Binary query and noise in (0,.5) required')
    logp=np.log(np.array([.5,.5]))
    for x,y in examples:
        if x not in (0,1) or y not in (0,1):raise ValueError('Binary demonstrations required')
        for rule in range(2):
            logp[rule]+=np.log(1-noise if y==(x^rule) else noise)
    posterior=np.exp(logp-logp.max());posterior/=posterior.sum()
    likelihood=np.array([1-noise if (query^rule)==1 else noise for rule in range(2)])
    return float(posterior@likelihood),posterior


def demo():
    pretrained, pretrace=train(0.)
    tuned, trace=train(pretrained,True)
    examples=[(0,1),(1,0)]
    predictions=[condition(examples[:n],0)[0] for n in range(3)]
    return dict(pretrained_weight=pretrained, fine_tuned_weight=tuned,
                target_loss_before=loss_grad(pretrained,True)[0], target_loss_after=loss_grad(tuned,True)[0],
                pretraining_trace=pretrace, fine_tuning_trace=trace,
                conditioning_predictions=predictions, posterior_inverted=float(condition(examples,0)[1][1]),
                scope='Separate toy mechanisms: logistic parameter update versus fixed Bayesian rules; not GPT in-context implementation')


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

The learned weight changes from about 2.197224 to −2.197223. On the inverted task, loss falls from about 2.082862 to 0.325083 nats. That final value is close to the binary entropy of 0.1; zero loss would be the wrong expectation for the soft targets.

The separate condition function leaves the two rule likelihoods and their prior fixed. For query zero, using zero, one and two inversion demonstrations gives probabilities 0.5, 0.82 and about 0.890244. It accumulates log probabilities before normalizing, so a long consistent demonstration list does not underflow the product into zero. The tests check both training gradients by centered finite differences, both known optima, conflicting demonstrations and input-list preservation.

With two rules and mm demonstrations, conditioning costs O(m)O(m) time and constant auxiliary memory. Each scalar gradient step costs constant time here. These costs describe only the toy. Transformer attention, context length, parameter count and caching determine the cost of actual GPT inference and training.

A prompt is neither a weight update nor a guarantee

This analogy has an explicit hypothesis set containing the correct rule. Natural tasks need not fit such a set, and real demonstrations can be ambiguous, mislabeled or misleading. Our posterior is invariant to demonstration order because multiplication is commutative. A language model’s positional computation need not share that invariance. The program therefore tests a conceptual distinction, not a mechanism attributed to GPT.

The logistic fine-tuning example also uses different machinery from the Bayesian predictor. Comparing their losses would not be a controlled comparison of fine-tuning against prompting. To study that question empirically, hold the underlying model, task split, evaluation examples and data access fixed, then report optimization and inference budgets separately.

Neither the autoregressive objective nor the name GPT specifies factual reliability, dialogue behavior or instruction following. The cited historical reports concern particular training and evaluation setups. They do not justify extending one result to all later products or asserting that in-context demonstrations reliably solve every task. This chapter adopts no benchmark score from those reports.

Locate the change

  1. A fixed model produces a different answer after demonstrations are added. Must its parameters have changed?

Answer: No. Different conditioning inputs can change activations and output probabilities with exactly the same stored parameters. A parameter update requires an additional learning operation.

  1. Why is the toy identity rule’s optimal logistic weight log⁡9\log9?

Answer: At input plus one, the desired probability is 0.9. Its odds are 0.9/0.1=90.9/0.1=9, whose logarithm is log⁡9\log9. The symmetric negative input then receives probability 0.1. Inverting the labels changes the optimum’s sign.

  1. What posterior results from contradictory examples (0,1) and (0,0) under the equal-prior noisy rules?

Answer: Each rule assigns likelihood 0.9×0.10.9\times0.1 to the pair. The likelihoods cancel in the posterior odds, leaving probability one-half for each rule. Repetition does not guarantee stronger evidence for one rule when the examples conflict.

  1. Why does the two-demonstration prediction remain below 0.9 rather than becoming one?

Answer: There is still posterior uncertainty about the rule, and even a known rule has 0.1 observation noise. Averaging the two likelihoods yields about 0.890244. A confident rule posterior is not the same quantity as a deterministic label probability.

Read the training protocol and the evaluation protocol separately

The 2018 report is useful for following how pretraining feeds a supervised adaptation objective. GPT-2 is useful for understanding how tasks can be represented through text conditioning. GPT-3 makes the number of supplied demonstrations and the absence of inference-time weight updates explicit. These are connected developments, not interchangeable experimental protocols. Original GPT GPT-2 GPT-3

For a small project, create a held-out set of binary rules and compare a fixed hypothesis learner with a fitted classifier. Record what each method knew before seeing the examples. Then introduce a rule absent from the fixed hypothesis set. That change tests a failure the clean two-rule example cannot show, and gives a concrete reason to distinguish model capacity, adaptation data and evaluation conditions.

Make a prediction, then check

What changes during GPT-3 few-shot inference as defined in the paper?

Choose one answer

Learning objectives

  • Follow the original GPT training objective and distinguish parameter updates from fixed-model conditioning.
  • Derive the logistic optimum and the fixed-rule posterior without conflating their learning mechanisms.
  • Distinguish protocol claims in the original GPT, GPT-2 and GPT-3 reports.

Prerequisites & connections

Explore related knowledge →

References

  1. Improving Language Understanding by Generative Pre-Training
    Alec Radford; Karthik Narasimhan; Tim Salimans; Ilya Sutskever · 2018
  2. Language Models are Unsupervised Multitask Learners
    Alec Radford; Jeffrey Wu; Rewon Child; David Luan; Dario Amodei; Ilya Sutskever · 2019
  3. Language Models are Few-Shot Learners — NeurIPS 2020
    Tom B. Brown; Benjamin Mann; Nick Ryder; Melanie Subbiah; Jared Kaplan; Prafulla Dhariwal; Arvind Neelakantan; Pranav Shyam; Girish Sastry; Amanda Askell; Sandhini Agarwal; Ariel Herbert-Voss; Gretchen Krueger; Tom Henighan; Rewon Child; Aditya Ramesh; Daniel M. Ziegler; Jeffrey Wu; Clemens Winter; Christopher Hesse; Mark Chen; Eric Sigler; Mateusz Litwin; Scott Gray; Benjamin Chess; Jack Clark; Christopher Berner; Sam McCandlish; Alec Radford; Ilya Sutskever; Dario Amodei · 2020

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-20 · Single AI author checked original GPT3.1-3.3/4.1, GPT2 task conditioning and GPT3 conference section2 definitions. Six paired equations and four explained exercises; scalar logistic pretraining/adaptation and separate fixed-rule Bayes conditioning. Gradient checks and exact posterior81/82; not GPT internal inference or a controlled performance comparison of prompting versus tuning.

  • Single AI author checked original GPT3.1-3.3/4.1, GPT2 task conditioning and GPT3 conference section2 definitions. Six paired equations and four explained exercises; scalar logistic pretraining/adaptation and separate fixed-rule Bayes conditioning. Gradient checks and exact posterior81/82; not GPT internal inference or a controlled performance comparison of prompting versus tuning.
  • Four computed SVG variants per topic. Fifteen numeric/geometry tests and42 responsive cases passed; fourteen final Chinese-mobile/English-desktop screenshots actually inspected. Initial English mobile-heading clipping and corrections preserved. Full article acceptance recorded separately.

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.