GPT-1, GPT-2, GPT-3: From Fine-Tuning to In-Context Learning, Recomputed from the Papers
GPT-1, GPT-2 and GPT-3 are three scale-ups of one decoder-only Transformer; what changes is how a task reaches the model: fine-tuning, zero-shot text, or few-shot examples in the context. This page rechecks the papers' numbers and measures perplexity and in-context learning on GPT-2.
On this page
- Why read the three papers together
- How the three papers get a model to do a task
- GPT-1: pre-training, then fine-tuning
- GPT-2: writing the task as text
- GPT-3: writing the task into the context
- Hands-on check: recompute the numbers in the papers
- Parameters: one formula, three reconciliations
- GPT-3’s Table 2.1: two rows that disagree
- The data mixture: WebText2’s epochs cannot be recomputed
- Compute: Table D.1 is self-consistent, but a caption disagrees with the table
- Summary of the check
- Experiment 1: can GPT-2’s perplexity reproduce the paper’s Table 3?
- Experiment 2: in-context learning in GPT-2, and what the examples actually do
- Limits and what came after
- What to take away from the three papers
- Further reading
- FAQ
GPT-1 (2018), GPT-2 (2019) and GPT-3 (2020) are three scale-ups of one recipe: a decoder-only Transformer trained to predict the next token, with the model and the data made bigger each time. What really differs between the papers is how a task reaches the model. GPT-1 pre-trains and then fine-tunes once per task. GPT-2 stops training per task and writes the task as text, to be done zero-shot. GPT-3 puts the task description and a few examples in the context and again updates nothing, which the paper calls in-context learning (Figure 1).
This page does two things with the three original papers. Check: recompute what can be recomputed. The parameter count follows from one formula, and the formula, the Hugging Face model classes and the checkpoint files agree exactly for all four GPT-2 sizes; Table 2 of the GPT-2 paper prints 117M, 345M, 762M and 1542M, which are 6.4%, 2.8%, 1.6% and 1.0% below the true values (OpenAI’s repository admits the original counts were wrong). In GPT-3’s Table 2.1, the 13B model’s is printed as 5140 while heads times head size is 5120, and with 5120 the formula matches Table D.1’s parameter count to within 0.03%. In Table 2.2, WebText2 is printed at 2.9 epochs but recomputes to 3.47 from tokens and weights (the weights count examples rather than tokens, so the gap may come from there). Table D.1’s compute agrees with to within 0.21%, so that table is self-consistent. Measure: this page runs two experiments on the four GPT-2 checkpoints. The first is perplexity on WikiText-2: de-tokenized and normalized per word it gives 29.57, 22.80, 19.82 and 18.01, within 2% of the paper’s Table 3 values of 29.41, 22.76, 19.93 and 18.34, while per token on the text as is it is only 12.91 to 19.87, so a perplexity must be reported together with its unit. The second is in-context learning on three toy tasks: accuracy jumps most as the examples go from 0 to 1 (upper-casing for GPT-2 xl goes from 0.0% to 92.5%) and is then mostly flat, and two-digit addition stays near zero; after rotating the answers in the examples, upper-casing falls from 91.7% to 35.0% (xl) and capitals fall less (xl from 94.2% to 69.2%), so the examples supply both the format and the pairing, in proportions that depend on the task.
Why read the three papers together
- They are where the three “pre-train, then adapt” interfaces come from. Fine-tuning, zero-shot and few-shot in-context learning later turned into task-head fine-tuning, instruction prompting and few-shot prompting; prompt engineering, RAG and agents all live on the line of “put the task in the input” (see Prompt Engineering).
- They fixed the decoder-only line. BERT went bidirectional in the same year while the GPT series stayed autoregressive; most mainstream open models since follow the latter (see Modern LLM Architecture).
- GPT-3 treated scale as a research variable and carried it through. Eight sizes, one dataset, one family of settings, and few-shot curves that rise faster with scale than zero-shot ones (Figure 1.3 of the paper) are the most direct downstream evidence that scale lifts capability.
- The numbers can be checked. Parameters, training tokens, the data mixture and compute can all be recomputed in a few lines of code, and a few of them do not agree with themselves, which makes a good exercise.
- Neighbors on this site. Scaling laws are in the Scaling Laws paper note; the correction to GPT-3’s data-to-model ratio is in the Chinchilla note; making GPT-3 follow instructions is in the InstructGPT note; the bidirectional line is in the BERT note; the network itself is in the Attention Is All You Need note; and the training pipeline and scaling laws are in Training Pipeline and Scaling Laws.
GPT-1 and GPT-2 were read from the PDFs OpenAI hosts (links at the end); GPT-3 from arXiv v4. Table numbers were taken from the PDF layout text, and Tables 2.1 and D.1 were also checked against rendered pages. The GPT-2 checkpoint parameter totals are read by this page’s code from the safetensors file headers, with no network access.
How the three papers get a model to do a task
The three papers use almost the same network; the difference is where the task comes in:
| Item | GPT-1 (2018) | GPT-2 (2019) | GPT-3 (2020) |
|---|---|---|---|
| Source | OpenAI technical report | OpenAI technical report | arXiv 2005.14165, NeurIPS 2020 |
| Size | 12 layers, , about 117M | 12 to 48 layers, to 1600, 124M to 1.56B | 12 to 96 layers, to 12288, 125M to 175B |
| Context | 512 | 1024 | 2048 |
| Vocabulary | BPE, 40,000 merges | Byte-level BPE, 50,257 | Same as GPT-2 |
| Training data | BooksCorpus, over 7,000 unpublished books | WebText, about 8 million documents, 40 GB | Filtered Common Crawl plus four sources, 300B tokens of training |
| Doing a task | Fine-tuning: a linear output layer plus an auxiliary language-modeling loss, one set of weights per task | Zero-shot: the task is written as text, one set of weights | Few-shot: description and examples in the context, one set of weights |
| Main evidence | State of the art on 9 of 12 datasets | State of the art zero-shot on 7 of 8 language-modeling datasets | Over two dozen NLP datasets, few-shot improving faster with scale |
GPT-1: pre-training, then fine-tuning
The paper is Improving Language Understanding by Generative Pre-Training (Radford et al., OpenAI, 2018). Step one is unsupervised pre-training: a 12-layer Transformer decoder with a 512-token context is trained with the standard language-modeling objective on BooksCorpus (over 7,000 unpublished books), for 100 epochs on batches of 64 sequences. Step two is supervised fine-tuning: each task adds a linear layer on top of the last layer’s output and continues training on the task’s labeled data. The paper also keeps the language-modeling loss as an auxiliary objective, giving the total loss
where is the language-modeling loss and is the task loss. Structured inputs such as sentence pairs or document-question-answer triples are turned into one token sequence by a “traversal-style” conversion with start and end symbols and a delimiter, so one model handles all kinds of tasks without architectural changes.
The result was a new state of the art on 9 of 12 datasets: 8.9% better on commonsense reasoning (Stories Cloze), 5.7% on question answering (RACE) and 1.5% on textual entailment (MultiNLI). The paper also observed that the auxiliary language-modeling loss helps on larger datasets and not on smaller ones. The cost is clear as well: one set of weights and one fine-tuning run per task, and labeled data is still required. That is exactly what GPT-2 set out to remove.
GPT-2: writing the task as text
The paper is Language Models are Unsupervised Multitask Learners (Radford et al., OpenAI, 2019). Its argument: a supervised system estimates , but a general system should also condition on the task, . The task itself can be written in words, so a strong enough language model that predicts the next token on web text is already learning many tasks, because the text contains naturally occurring demonstrations of translation, question answering, summarization and so on.
To test this the paper built WebText: pages linked from Reddit posts that received at least 3 karma, cleaned to slightly over 8 million documents and 40 GB of text, with Wikipedia removed to avoid overlap with evaluation sets. The architecture is GPT-1’s with a few changes: layer normalization moves to the input of each sub-block (pre-norm) with one more after the final self-attention block; the weights of residual layers are scaled at initialization by ( is the number of residual layers); the vocabulary grows to 50,257 byte-level BPE tokens; the context grows from 512 to 1024; and the batch size is 512. Four sizes were trained at roughly log-uniform spacing. The paper says the smallest is equivalent to the original GPT, the second smallest to the largest BERT model, and the largest is GPT-2.
Zero-shot, it set a new state of the art on 7 of 8 language-modeling datasets, with WikiText-2 perplexity falling from 39.14 to 18.34. The one it did not beat is 1BW (One Billion Word benchmark), which the paper explains by its sentence-level shuffling destroying all long-range structure. One sentence from the abstract is worth remembering: capacity is essential to zero-shot task transfer and improves performance in a log-linear fashion across tasks, while the largest model still underfits WebText.
GPT-3: writing the task into the context
The paper is Language Models are Few-Shot Learners (Brown et al., OpenAI, arXiv 2005.14165, NeurIPS 2020). The architecture follows GPT-2 (including initialization, pre-norm and reversible tokenization) with two differences: the layers alternate dense and locally banded sparse attention, similar to the Sparse Transformer, and the context doubles to 2048. The paper trains 8 sizes (Table 2.1), from 125 million to 175 billion parameters across three orders of magnitude, and every model sees only 300 billion tokens. The data is filtered and deduplicated Common Crawl (570 GB after filtering, roughly 400 billion BPE tokens) mixed with WebText2, two book corpora Books1 and Books2, and English Wikipedia (Table 2.2); higher-quality sources are sampled more often, so Common Crawl and Books2 are seen less than once and the others two to three times.
There are four ways to adapt to a task, all at inference time: fine-tuning updates gradients, and the other three do not update parameters and only put things in the context. Zero-shot gives only a natural-language description; one-shot adds one demonstration; few-shot puts in as many demonstrations as fit in the context window, typically 10 to 100. The paper calls this learning inside the context in-context learning, and treats it as the inner loop of meta-learning.
Results are reported as three numbers side by side. On TriviaQA accuracy is 64.3%, 68.0% and 71.2%, and on CoQA the F1 is 81.5, 84.0 and 85.0 (zero-, one- and few-shot). On the aggregate over 42 accuracy-denominated benchmarks, zero-shot performance improves steadily with model size and few-shot improves more rapidly, which the paper takes as evidence that larger models are more proficient at in-context learning (Figure 1.3).
Hands-on check: recompute the numbers in the papers
The script trains nothing; it only does arithmetic. It copies the paper’s tables and formulas into code and reconciles them with the real parameter counts of the Hugging Face checkpoints. It has four parts, in the order of the output: GPT-2’s parameter counts (the formula, the transformers model classes and the checkpoint file headers, with GPT-1 added), GPT-3’s Table 2.1, the data mixture and epochs of Table 2.2, and the compute of Table D.1. Environment: Python 3.14.3, PyTorch 2.10.0, transformers 5.3.0 (models are built on the meta device only to count parameters, using no memory), NumPy 2.4.2, CPU; the checkpoints are Hugging Face’s gpt2, gpt2-medium, gpt2-large and gpt2-xl (now under openai-community, MIT license).
Full code (about 158 lines)
"""Recheck numbers in the three GPT papers: the parameter
formula, the checkpoints, and GPT-3's Tables 2.1, 2.2 and D.1"""
import glob
import json
import math
import os
import struct
import torch
from transformers import (GPT2Config, GPT2LMHeadModel, OpenAIGPTConfig,
OpenAIGPTLMHeadModel)
from transformers.utils import logging as hf_logging
hf_logging.set_verbosity_error()
def width(s):
return sum(2 if ord(c) > 0x2e80 else 1 for c in s)
def cols(cells, widths):
"""align by display width: first column left, the rest right
(a CJK character takes two cells)"""
out = " " + cells[0] + " " * (widths[0] - width(cells[0]))
for c, w in zip(cells[1:], widths[1:]):
out += " " * (w - width(c)) + c
return out
def formula(L, d, V, ctx, final_ln=True):
"""embeddings plus positions, 12d^2+13d per block, plus the final
layer norm 2d"""
block = 12 * d * d + 13 * d
return (V + ctx) * d + L * block + (2 * d if final_ln else 0)
def hf_count(cls, cfg):
"""build the model on the meta device and count: no memory"""
with torch.device("meta"):
model = cls(cfg)
return sum(p.numel() for p in model.parameters())
def ckpt_count(name):
"""read the safetensors header; 4-D tensors are attention-mask
buffers, not parameters"""
home = os.path.expanduser("~/.cache/huggingface/hub")
path = glob.glob(f"{home}/models--{name}/snapshots/*/model.safetensors")[0]
with open(path, "rb") as fh:
head = json.loads(fh.read(struct.unpack("<Q", fh.read(8))[0]))
head.pop("__metadata__", None)
size = {k: math.prod(v["shape"]) for k, v in head.items()}
masks = sum(n for k, n in size.items() if len(head[k]["shape"]) == 4)
return sum(size.values()) - masks, masks, sum(size.values())
# ---- 1. GPT-1 and GPT-2: formula, HF classes, checkpoints, paper ----
GPT2 = (("gpt2", "GPT-2 small", 12, 768, 12, "117M", 117e6),
("gpt2-medium", "GPT-2 medium", 24, 1024, 16, "345M", 345e6),
("gpt2-large", "GPT-2 large", 36, 1280, 20, "762M", 762e6),
("gpt2-xl", "GPT-2 xl", 48, 1600, 25, "1542M", 1542e6))
print("1. Parameters: formula, HF classes, checkpoints, GPT-2 paper Table 2")
W1 = (15, 10, 24, 16)
print(cols(("model", "paper", "formula = HF = file", "excess"), W1))
agree, extra = True, []
for hub, name, L, d, h, paper, pn in GPT2:
f = formula(L, d, 50257, 1024)
hf = hf_count(GPT2LMHeadModel, GPT2Config(n_layer=L, n_embd=d, n_head=h))
ck, mask, total = ckpt_count(hub)
agree = agree and f == hf == ck
extra.append((name, mask, total))
print(cols((name, paper, f"{f:,}", f"{f / pn - 1:.1%}"), W1))
print(f" formula, HF class and checkpoint (mask buffers removed) are "
f"equal for all four: {agree}")
for name, mask, total in extra[:1]:
print(f" the file also holds attention-mask buffers: {name} has "
f"{mask:,}, {total:,} in all")
g1 = OpenAIGPTConfig()
f1 = formula(g1.n_layer, g1.n_embd, g1.vocab_size, g1.n_positions, False)
h1 = hf_count(OpenAIGPTLMHeadModel, g1)
print(f" GPT-1 ({g1.n_layer} layers, d={g1.n_embd}, vocabulary "
f"{g1.vocab_size:,}, context {g1.n_positions},\n"
f" no final layer norm): formula {f1:,}, HF class {h1:,}")
small = formula(12, 768, 50257, 1024)
emb = (50257 + 1024) * 768 - (g1.vocab_size + g1.n_positions) * 768
assert small - f1 == emb + 2 * 768
print(f" GPT-2 small has {small - f1:,} more parameters than GPT-1: "
f"{emb:,} more in the\n token and position embeddings, "
f"{2 * 768:,} in the final layer norm")
# ---- 2. GPT-3: the parameter columns of Tables 2.1 and D.1 ----
# fields: name, layers, d_model, heads, d_head, then the params
# (M), PF-days and FLOPs of Table D.1; Tables 2.1 and D.1 are copied as printed
G3 = (("Small", 12, 768, 12, 64, 125, 2.60, 2.25e20),
("Medium", 24, 1024, 16, 64, 356, 7.42, 6.41e20),
("Large", 24, 1536, 16, 96, 760, 15.8, 1.37e21),
("XL", 24, 2048, 24, 128, 1320, 27.5, 2.38e21),
("2.7B", 32, 2560, 32, 80, 2650, 55.2, 4.77e21),
("6.7B", 32, 4096, 32, 128, 6660, 139, 1.20e22),
("13B", 40, 5140, 40, 128, 12850, 268, 2.31e22),
("175B", 96, 12288, 96, 128, 174600, 3640, 3.14e23))
print("\n2. GPT-3 Table 2.1 shapes against the parameters of Table D.1\n"
" (V=50,257, n_ctx=2048)")
W2 = (8, 5, 9, 17, 11, 9, 8)
print(cols(("model", "L", "d_model", "heads x d_head",
"formula M", "D.1 M", "diff"), W2))
bad = []
for name, L, d, h, dh, p1, pf, fl in G3:
f = formula(L, d, 50257, 2048) / 1e6
if h * dh != d:
bad.append((name, h, dh, h * dh, d))
print(cols((name, str(L), str(d), f"{h}x{dh}={h * dh}", f"{f:,.1f}",
f"{p1:,}", f"{f / p1 - 1:.2%}"), W2))
for name, h, dh, prod, d in bad:
print(f" heads x d_head disagrees with d_model: {name}, "
f"{h}x{dh}={prod}, d_model printed as {d}")
f13 = formula(40, 5120, 50257, 2048) / 1e6
print(f" 13B with d_model 5120: formula {f13:,.1f}M, "
f"{f13 / 12850 - 1:.2%} from the 12,850M of D.1")
# ---- 3. Table 2.2: mixture weights and epochs ----
MIX = (("Common Crawl", 410, 60, 0.44), ("WebText2", 19, 22, 2.9),
("Books1", 12, 8, 1.9), ("Books2", 55, 8, 0.43),
("Wikipedia", 3, 3, 3.4))
print("\n3. Table 2.2: epochs per dataset recomputed from the mixture\n"
" weights (300B tokens)")
W3 = (16, 10, 8, 10, 13, 13)
print(cols(("dataset", "tokens B", "weight", "printed",
"recomputed", "implied w"), W3))
imp = 0
for name, tok, w, ep in MIX:
imp += ep * tok / 300
print(cols((name, str(tok), f"{w}%", f"{ep:.2f}",
f"{300 * w / 100 / tok:.2f}", f"{ep * tok / 300:.1%}"), W3))
print(f" printed weights sum to {sum(m[2] for m in MIX)}%, implied weights "
f"to {imp:.1%}")
# ---- 4. Table D.1: compute = 6 x parameters x tokens ----
print("\n4. Table D.1: 6 x parameters x 300B tokens against the printed\n"
" FLOPs and PF-days")
print(" (1 PF-day = 8.64e19 FLOPs)")
W4 = (8, 10, 14, 14, 8, 14)
print(cols(("model", "params M", "printed PFd", "recomputed",
"diff", "tokens/param"), W4))
worst = 0.0
for name, L, d, h, dh, p1, pf, fl in G3:
flops = 6 * p1 * 1e6 * 300e9
worst = max(worst, abs(flops / fl - 1))
print(cols((name, f"{p1:,}", f"{float(f'{pf:.3g}'):,g}",
f"{flops / 8.64e19:,.2f}",
f"{flops / 8.64e19 / pf - 1:.2%}",
f"{300e9 / (p1 * 1e6):,.2f}"), W4))
print(f" largest deviation from the printed FLOPs: {worst:.1%}")
big, rob = G3[4], 355
print(f" Figure 2.2's caption: GPT-3 \"3B\" is almost 10x larger than\n"
f" RoBERTa-Large (355M), both near 50 PF-days; the table row\n"
f" is 2.7B: {big[5] / rob:.2f}x, {big[6]} and 49.3 PF-days")
Parameters: one formula, three reconciliations
The parameter count of a decoder-only Transformer follows from its block structure. With layers, width , vocabulary and context length : the token and learned position embeddings together have parameters (the output layer shares weights with the token embedding and is not counted again); each block has two layer norms ( each), the attention QKV and output projections () and the two-layer feed-forward network (), giving ; GPT-2 and GPT-3 add one more layer norm at the end, and GPT-1 does not:
1. Parameters: formula, HF classes, checkpoints, GPT-2 paper Table 2
model paper formula = HF = file excess
GPT-2 small 117M 124,439,808 6.4%
GPT-2 medium 345M 354,823,168 2.8%
GPT-2 large 762M 774,030,080 1.6%
GPT-2 xl 1542M 1,557,611,200 1.0%
formula, HF class and checkpoint (mask buffers removed) are equal for all four: True
the file also holds attention-mask buffers: GPT-2 small has 12,582,912, 137,022,720 in all
GPT-1 (12 layers, d=768, vocabulary 40,478, context 512,
no final layer norm): formula 116,534,784, HF class 116,534,784
GPT-2 small has 7,905,024 more parameters than GPT-1: 7,903,488 more in the
token and position embeddings, 1,536 in the final layer norm
For all four sizes the formula, the transformers model class and the checkpoint file header (with attention-mask buffers removed) agree exactly, so the numbers printed in the paper’s Table 2 are indeed too small, by 6.4%, 2.8%, 1.6% and 1.0%. OpenAI’s own repository acknowledges this: the original counts, in its blog posts and paper, were wrong, and the small model had been called 117M and the medium 345M; the model card lists 124M, 355M, 774M and 1.5 billion, consistent with the results here.
The output also shows where 117M came from. The GPT-1 paper never printed a total parameter count; counting its structure (12 layers, , vocabulary 40,478, context 512, no final layer norm) gives 116,534,784, about 117 million. The GPT-2 paper says its smallest model is equivalent to the original GPT, so the label was carried over. The real GPT-2 small has a bigger vocabulary and context and one more final layer norm, so it has 7,905,024 more parameters than GPT-1: 7,903,488 more in the token and position embeddings and 1,536 in the layer norm, which add up exactly. The “345M” of the second smallest is similar: the paper says it is equivalent to the largest BERT model, and the real value is 354,823,168.
One more common source of confusion: in Hugging Face’s metadata, gpt2 has 137,022,720 parameters in total, more than 124M. The checkpoint file also stores 12 causal-mask buffers of , 12,582,912 numbers in all, which are not learnable parameters; the file total in the output above matches the Hub metadata (queried on 13 November 2026), and subtracting the masks gives 124,439,808.
GPT-3’s Table 2.1: two rows that disagree
Table 2.1 gives the layers, , heads and head size of the 8 sizes, and the parameter counts are in Table D.1. Putting each row into the same formula (, ) and reconciling with Table D.1 gives differences of at most 0.32%, except for the 13B row:
2. GPT-3 Table 2.1 shapes against the parameters of Table D.1
(V=50,257, n_ctx=2048)
model L d_model heads x d_head formula M D.1 M diff
Small 12 768 12x64=768 125.2 125 0.18%
Medium 24 1024 16x64=1024 355.9 356 -0.04%
Large 24 1536 16x96=1536 760.3 760 0.04%
XL 24 2048 24x128=3072 1,315.7 1,320 -0.32%
2.7B 32 2560 32x80=2560 2,651.6 2,650 0.06%
6.7B 32 4096 32x128=4096 6,658.4 6,660 -0.02%
13B 40 5140 40x128=5120 12,952.9 12,850 0.80%
175B 96 12288 96x128=12288 174,604.3 174,600 0.00%
heads x d_head disagrees with d_model: XL, 24x128=3072, d_model printed as 2048
heads x d_head disagrees with d_model: 13B, 40x128=5120, d_model printed as 5140
13B with d_model 5120: formula 12,853.4M, 0.03% from the 12,850M of D.1
The 13B model’s is printed as 5140, which disagrees with its own heads times head size, . Put into the formula, 5140 is 0.80% above Table D.1’s parameter count, while 5120 differs by only 0.03%, so 5140 is most likely a typo for 5120. The XL row is a different case: 24 heads times a head size of 128 is 3072, which does not match . The parameter count depends only on and not on the number of heads, so the count cannot tell whether the heads or the head size is misprinted; all one can say is that the row is inconsistent with itself.
The data mixture: WebText2’s epochs cannot be recomputed
Table 2.2 lists, for five datasets, the tokens, the weight in the training mix and the epochs elapsed when training for 300 billion tokens. Epochs should equal weight × 300 billion ÷ dataset tokens; the recomputation is below, and the last column is the weight implied by the printed epochs. One premise matters: the paper defines the weight as the fraction of examples drawn from each dataset during training, while this calculation treats it as a fraction of tokens, so when example lengths differ across datasets the recomputation will differ from the printed numbers. That is not necessarily an error in the paper:
3. Table 2.2: epochs per dataset recomputed from the mixture
weights (300B tokens)
dataset tokens B weight printed recomputed implied w
Common Crawl 410 60% 0.44 0.44 60.1%
WebText2 19 22% 2.90 3.47 18.4%
Books1 12 8% 1.90 2.00 7.6%
Books2 55 8% 0.43 0.44 7.9%
Wikipedia 3 3% 3.40 3.00 3.4%
printed weights sum to 101%, implied weights to 97.4%
Common Crawl and Books2 agree, and Books1 and Wikipedia differ within rounding (slightly more epochs, slightly less weight). WebText2 does not agree: 2.9 epochs are printed, while a 22% weight gives 3.47; conversely, 2.9 epochs corresponds to only an 18.4% weight. The five weights add up to 101%, which is within rounding, and the weights implied by the epochs add up to 97.4%. Whether WebText2’s gap comes from example length, the paper does not give example lengths per dataset, so there is no way to tell; if someone wanted to reproduce GPT-3’s data mixture, whether to use the weight column or the epoch column is not stated.
Compute: Table D.1 is self-consistent, but a caption disagrees with the table
Table D.1 estimates total compute as training tokens × FLOPs per token ≈ 6 × parameters (ignoring attention, which the paper says is usually under 10% of the total), and converts it to petaflop/s-days (one petaflop/s sustained for a day, FLOPs). The recomputation matches the printed numbers:
4. Table D.1: 6 x parameters x 300B tokens against the printed
FLOPs and PF-days
(1 PF-day = 8.64e19 FLOPs)
model params M printed PFd recomputed diff tokens/param
Small 125 2.6 2.60 0.16% 2,400.00
Medium 356 7.42 7.42 -0.04% 842.70
Large 760 15.8 15.83 0.21% 394.74
XL 1,320 27.5 27.50 0.00% 227.27
2.7B 2,650 55.2 55.21 0.02% 113.21
6.7B 6,660 139 138.75 -0.18% 45.05
13B 12,850 268 267.71 -0.11% 23.35
175B 174,600 3,640 3,637.50 -0.07% 1.72
largest deviation from the printed FLOPs: 0.2%
Figure 2.2's caption: GPT-3 "3B" is almost 10x larger than
RoBERTa-Large (355M), both near 50 PF-days; the table row
is 2.7B: 7.46x, 55.2 and 49.3 PF-days
The largest deviation is 0.2%, so the table is self-consistent. It also gives a number worth remembering: the 175B model sees only 1.72 tokens per parameter, against 23.35 for 13B and 2,400 for Small. The caption of Figure 2.2 is explicit: following the analysis of Kaplan et al., it trains much larger models on many fewer tokens than is typical, so although GPT-3 “3B” is almost 10 times larger than RoBERTa-Large (355M), both took roughly 50 petaflop/s-days of pre-training compute. What does not quite agree is that sentence: the table’s corresponding row is 2.7B, only 7.46 times larger than 355M, at 55.2 versus 49.3 petaflop/s-days, so “almost 10 times” is a rough statement.
Summary of the check
| Where | Printed in the paper | Recomputed | Verdict |
|---|---|---|---|
| GPT-2 Table 2 | 117M, 345M, 762M, 1542M | 124.4M, 354.8M, 774.0M, 1,557.6M | 1.0% to 6.4% too small, repository admits it |
| GPT-3 Table 2.1, 13B | 5140 | heads × head size 5120, and with it 0.03% off | Typo |
| GPT-3 Table 2.1, XL | 24 heads, head size 128, 2048 | Self-contradictory, counts cannot tell | |
| GPT-3 Table 2.2 | WebText2 2.9 epochs, weights sum to 101% | 3.47 epochs, implied weight 18.4% | Not reproducible by tokens, weights count examples |
| GPT-3 Figure 2.2 caption | ”almost 10x” | 7.46x (the table’s 2.7B) | Rough |
| GPT-3 text vs Table 3.9 | Three-digit addition 80.2% and 80.4% | Two writings of one number | Text and table disagree |
| GPT-3 Table D.1 | FLOPs and petaflop/s-days | Within 0.21% | Self-consistent |
Experiment 1: can GPT-2’s perplexity reproduce the paper’s Table 3?
Table 3 of the paper gives the zero-shot perplexity of the four GPT-2 sizes on WikiText-2: 29.41, 22.76, 19.93 and 18.34, against 39.14 for the previous best. Perplexity is the exponential of an average negative log-likelihood, and the paper says the average is taken per canonical prediction unit, usually a character, a byte or a word. It also says the main results use invertible de-tokenizers that strip tokenization and pre-processing artifacts, which improved GPT-2’s perplexity by 2.5 to 5. It does not say which unit WikiText-2 uses or how long the evaluation window was. The unit, the text processing and the window each change the number, so this section asks a checkable question: with the public checkpoints and one reasonable protocol, can the four numbers be reproduced?
The script puts the three choices in plain view:
- Text. The WikiText-2 test set (
wikitext-2-v1fromSalesforce/wikitext, 4,358 rows) comes with tokenization artifacts:@-@, spaces before punctuation, and 15,218<unk>strings. The script uses the text as is (as-is) and a de-tokenized version produced by a heuristic written for this page (detok), which turns@-@,,,n'tand so on back into normal writing. The rules are not guaranteed to be invertible; they only estimate the effect of such processing. - Unit. One total negative log-likelihood, divided by three denominators: BPE tokens, words (split on whitespace, 241,211 of them) and units (words plus one end-of-line per row, 245,569). The last two denominators always come from the original text and do not change with de-tokenization.
- Window. A window of 1024 tokens with a stride of 512: each window scores only the 512 new tokens, so apart from the first window every token has at least 512 tokens of context. The whole text is preceded by one
<|endoftext|>.
The environment is the same as above (Apple M2 Max, PyTorch 2.10.0, transformers 5.3.0, float32, MPS). Each of the four checkpoints makes a full pass over both texts, and the whole script takes about 27 minutes.
Full code (about 119 lines)
"""Perplexity of the four GPT-2 sizes on the WikiText-2 test set, against
Table 3 of the paper. Usage: python exp_gpt_ppl.py [device] [max windows,
0 = all]"""
import glob
import math
import os
import re
import sys
import pandas as pd
import torch
import torch.nn.functional as F
from transformers import AutoTokenizer, GPT2LMHeadModel
from transformers.utils import logging as hf_logging
hf_logging.set_verbosity_error()
hf_logging.disable_progress_bar()
DEV = sys.argv[1] if len(sys.argv) > 1 else "mps"
MAXW = int(sys.argv[2]) if len(sys.argv) > 2 else 0
CTX, STRIDE = 1024, 512
MODELS = (("gpt2", "GPT-2 small", 29.41),
("gpt2-medium", "GPT-2 medium", 22.76),
("gpt2-large", "GPT-2 large", 19.93),
("gpt2-xl", "GPT-2 xl", 18.34))
home = os.path.expanduser("~/.cache/huggingface/hub")
path = glob.glob(f"{home}/datasets--Salesforce--wikitext/snapshots/*/"
"wikitext-2-v1/test-*.parquet")[0]
rows = pd.read_parquet(path)["text"].tolist()
text = "".join(rows)
n_words = len(text.split())
n_units = n_words + len(rows)
def cols(cells, widths):
"""align by display width: first column left, the rest right
(a CJK character takes two cells)"""
def width(s):
return sum(2 if ord(c) > 0x2e80 else 1 for c in s)
out = " " + cells[0] + " " * (widths[0] - width(cells[0]))
for c, w in zip(cells[1:], widths[1:]):
out += " " * (w - width(c)) + c
return out
def detok(s):
"""a heuristic de-tokenizer of my own: not shown to be invertible, it
only estimates what this kind of clean-up is worth"""
for a, b in ((" @-@ ", "-"), (" @,@ ", ","), (" @.@ ", ".")):
s = s.replace(a, b)
s = s.replace("n 't", "n't").replace(" 's", "'s")
s = re.sub(r" ([,.;:!?%)\]}])", r"\1", s)
s = re.sub(r"([(\[{$]) ", r"\1", s)
s = re.sub(r'" ([^"\n]*?) "', r'"\1"', s)
for a, b in (("= = = =", "===="), ("= = =", "==="), ("= =", "==")):
s = s.replace(a, b)
return s.replace(" \n", "\n").replace("\n ", "\n").lstrip(" ")
def nll_sum(model, ids):
"""sliding window: 1024 wide, stride 512, so every token
but the first window's has 512 tokens of context"""
total, done, count = 0.0, 0, 0
for begin in range(0, len(ids), STRIDE):
end = min(begin + CTX, len(ids))
x = torch.tensor([ids[begin:end]], device=DEV)
with torch.no_grad():
logits = model(x).logits[0].float()
nll = F.cross_entropy(logits[:-1], x[0, 1:], reduction="none")
total += nll[-(end - 1 - done):].cpu().double().sum().item()
done, count = end - 1, count + 1
if end == len(ids) or count == MAXW:
break
return total, done
tok = AutoTokenizer.from_pretrained("gpt2")
variants = ("as-is", "detok")
ids = {"as-is": [tok.eos_token_id] + tok(text)["input_ids"],
"detok": [tok.eos_token_id] + tok(detok(text))["input_ids"]}
print(f"WikiText-2 test (wikitext-2-v1): {len(rows):,} rows, "
f"{n_words:,} words ({text.count('<unk>'):,} of them <unk>), "
f"{n_units:,} units (words plus one end-of-line per row)")
print(f"window {CTX}, stride {STRIDE}, float32, device {DEV}")
print("start of the text:", repr(text[:90]))
print("after detok:", repr(detok(text)[:90]))
res = {}
for hub, name, paper in MODELS:
model = GPT2LMHeadModel.from_pretrained(hub, dtype=torch.float32)
model.to(DEV).eval()
for key in variants:
res[hub, key] = nll_sum(model, ids[key])
del model
if DEV == "mps":
torch.mps.empty_cache()
W1 = (14, 12, 11, 10, 10)
for key in variants:
print(f"\ntext: {key}")
print(cols(("model", "BPE tokens", "per token", "per word",
"per unit"), W1))
for hub, name, paper in MODELS:
tot, cnt = res[hub, key]
print(cols((name, f"{cnt:,}", f"{math.exp(tot / cnt):.2f}",
f"{math.exp(tot / n_words):.2f}",
f"{math.exp(tot / n_units):.2f}"), W1))
print("\nagainst Table 3 of the paper, WikiText2 (perplexity)")
W2 = (14, 8, 16, 8, 16, 8)
print(cols(("model", "paper", "detok per unit", "ratio",
"as-is per unit", "ratio"), W2))
for hub, name, paper in MODELS:
a = math.exp(res[hub, "detok"][0] / n_units)
b = math.exp(res[hub, "as-is"][0] / n_units)
print(cols((name, f"{paper:.2f}", f"{a:.2f}", f"{a / paper:.2f}",
f"{b:.2f}", f"{b / paper:.2f}"), W2))
gain = [math.exp(res[h, "as-is"][0] / n_units)
- math.exp(res[h, "detok"][0] / n_units) for h, _, _ in MODELS]
print("perplexity saved by de-tokenizing (per unit): "
+ ", ".join(f"{g:.2f}" for g in gain))
The output, as is (the two tables are the same negative log-likelihoods under different texts and different denominators):
WikiText-2 test (wikitext-2-v1): 4,358 rows, 241,211 words (15,218 of them <unk>), 245,569 units (words plus one end-of-line per row)
window 1024, stride 512, float32, device mps
start of the text: ' = Robert <unk> = \n Robert <unk> is an English film , television and theatre actor . He ha'
after detok: '= Robert <unk> =\nRobert <unk> is an English film, television and theatre actor. He had a g'
text: as-is
model BPE tokens per token per word per unit
GPT-2 small 292,943 19.87 37.71 35.36
GPT-2 medium 292,943 15.58 28.09 26.47
GPT-2 large 292,943 13.76 24.14 22.81
GPT-2 xl 292,943 12.91 22.34 21.15
text: detok
model BPE tokens per token per word per unit
GPT-2 small 276,883 19.12 29.57 27.85
GPT-2 medium 276,883 15.24 22.80 21.57
GPT-2 large 276,883 13.49 19.82 18.79
GPT-2 xl 276,883 12.41 18.01 17.11
against Table 3 of the paper, WikiText2 (perplexity)
model paper detok per unit ratio as-is per unit ratio
GPT-2 small 29.41 27.85 0.95 35.36 1.20
GPT-2 medium 22.76 21.57 0.95 26.47 1.16
GPT-2 large 19.93 18.79 0.94 22.81 1.14
GPT-2 xl 18.34 17.11 0.93 21.15 1.15
perplexity saved by de-tokenizing (per unit): 7.51, 4.90, 4.02, 4.04
The unit sets the scale. For one checkpoint and one text as is, the number is 12.91 to 19.87 per token, 22.34 to 37.71 per word and 21.15 to 35.36 per unit. There are 21% more tokens than words (292,943 against 241,211), so each word costs more than one token’s worth of prediction, and perplexity per word comes out roughly 70% to 90% above perplexity per token. Before comparing two perplexities, check that the units match: “the perplexity of GPT-2 large on WikiText-2” can be any of 13.76, 24.14, 22.81, 13.49, 19.82 and 18.79.
De-tokenizing moves the number the same way. It cuts the token count from 292,943 to 276,883 (about 5% fewer), and perplexity per word falls from 37.71 to 29.57 for small and from 22.34 to 18.01 for xl. The last line of the script gives the fall per unit, 7.51, 4.90, 4.02 and 4.04: the same direction as the paper, and larger than the 2.5 to 5 it reports. But these rules were written for this page, they are not the paper’s de-tokenizers, and they are not guaranteed to be invertible, so the two ranges cannot be compared directly.
Which combination comes closest to the paper? De-tokenized and per word gives 29.57, 22.80, 19.82 and 18.01, against the paper’s 29.41, 22.76, 19.93 and 18.34: within 2% at every size, and within 1% for the first three. My first guess, per unit (words plus line ends), is too low: de-tokenized it is only 0.95, 0.95, 0.94 and 0.93 of the paper’s number, and as is it is 1.20, 1.16, 1.14 and 1.15 times it (the comparison table at the end of the output). In the figure the dashed line is the paper, the blue line is de-tokenized per word and almost coincides with it, and the red line is as-is per word.
What this does and does not show. It shows that at all four sizes the paper’s numbers are compatible with perplexity per word on a de-tokenized text, and that the trend of lower perplexity with scale is there (29.57 falling to 18.01). It does not show that this is what the paper did. This cell was picked after seeing six combinations (two texts, three denominators), not stated as a hypothesis beforehand; the window length and stride also change the number, and this page used only 1024 and 512, without measuring their effect; and there are 15,218 <unk> strings (about 6% of the words) that GPT-2 has barely seen (the paper says the string occurs only 26 times in 40 billion bytes of WebText), and the paper does not say how it handled them. So the conclusion is “reproduced to within 2% under one reasonable protocol”, not “the paper’s evaluation protocol is confirmed”.
A more general lesson. Whenever you report a perplexity, state the unit, the text processing and the window. For one model on one test set this page has already seen numbers between 12.41 and 37.71, and which of them is “right” depends on what you want to compare with.
Experiment 2: in-context learning in GPT-2, and what the examples actually do
The GPT-3 paper’s claim is that larger models make better use of the examples in the context. GPT-3 itself cannot run on a laptop, so this experiment steps back and uses the four GPT-2 sizes to ask three smaller questions: how does accuracy change as the examples go from 0 to 16, how much does size matter, and does the pairing between question and answer in the examples matter, or only the format?
Three toy tasks, needing different things:
| Task | Pool | How an example is written | What it needs |
|---|---|---|---|
| Upper-casing | 60 English nouns | mountain => MOUNTAIN | copy and capitalize, no knowledge |
| Country to capital | 50 countries | France => Paris | knowledge, plus the output format |
| Two-digit addition | 200 pairs of numbers from 10 to 99 | 48 + 76 = 124 | arithmetic |
A prompt is one line of English task description (for example Name the capital of each country.), a blank line, examples and a final line with the query, for in 0, 1, 2, 4, 8 and 16. Each task has 3 draws of 40 queries; each query gets its own 16 examples (never including itself), and examples means the first of them, so the examples are nested across . Decoding is greedy with at most 6 new tokens, keeping the first line. Strict grading requires the whole line to equal the answer; lenient grading only requires the answer at the start of the line with no letter or digit right after it. Each number is therefore the mean of 120 prompts, and in a single draw of 40 one query is worth 2.5 percentage points. Sampling queries, sampling examples and rotating answers use independent seeds.
There are two more checks. One is the control: at the answers of the first 8 examples are rotated by some positions (same format, wrong pairing) to see how much accuracy drops. The other is the padding check: batched generation uses left padding, so GPT-2 small first compares batched and one-by-one greedy outputs on 12 prompts, to confirm that batching does not change the results.
The environment is as above (MPS, float32, eager attention). GPT-2 has had no instruction tuning, and the task description and the example format were each written once, with nothing tuned. The whole script takes about 3 minutes.
Full code (about 197 lines)
"""In-context learning with the four GPT-2 sizes: 0 to 16 demonstrations,
three tasks, three draws. Usage: python exp_gpt_icl.py [device]"""
import random
import re
import sys
import torch
from transformers import AutoTokenizer, GPT2LMHeadModel
from transformers.utils import logging as hf_logging
hf_logging.set_verbosity_error()
hf_logging.disable_progress_bar()
DEV = sys.argv[1] if len(sys.argv) > 1 else "mps"
KS = (0, 1, 2, 4, 8, 16)
DRAWS, NQ, SHUF_K = 3, 40, 8
MODELS = (("gpt2", "GPT-2 small"), ("gpt2-medium", "GPT-2 medium"),
("gpt2-large", "GPT-2 large"), ("gpt2-xl", "GPT-2 xl"))
CAPITALS = """Argentina Buenos Aires|Australia Canberra|Austria Vienna|
Belgium Brussels|Canada Ottawa|Chile Santiago|China Beijing|Cuba Havana|
Denmark Copenhagen|Egypt Cairo|Finland Helsinki|France Paris|Germany Berlin|
Greece Athens|Hungary Budapest|Iceland Reykjavik|India New Delhi|
Indonesia Jakarta|Iran Tehran|Iraq Baghdad|Ireland Dublin|Italy Rome|
Japan Tokyo|Kenya Nairobi|Lebanon Beirut|Mexico Mexico City|Morocco Rabat|
Nepal Kathmandu|Netherlands Amsterdam|Norway Oslo|Pakistan Islamabad|
Peru Lima|Philippines Manila|Poland Warsaw|Portugal Lisbon|
Romania Bucharest|Russia Moscow|Spain Madrid|Sweden Stockholm|
Switzerland Bern|Syria Damascus|Thailand Bangkok|Turkey Ankara|
Venezuela Caracas|Vietnam Hanoi|Afghanistan Kabul|Bangladesh Dhaka|
Ghana Accra|Libya Tripoli|Jamaica Kingston""".replace("\n", "").split("|")
WORDS = """apple banana river mountain window garden pencil bridge forest island
mirror candle ladder pillow basket bottle blanket village harbor meadow
rocket turtle button camera dinner engine farmer guitar hammer jacket
kitchen lemon marble needle orange parrot quarter ribbon saddle tunnel
umbrella valley wallet zebra anchor bucket cabin desert eagle fabric
galaxy helmet insect jungle kettle lantern magnet napkin oyster
planet""".split()
rng = random.Random("add-pool")
pairs = set()
while len(pairs) < 200:
pairs.add((rng.randint(10, 99), rng.randint(10, 99)))
POOL = {
"caps": [(w, w.upper()) for w in WORDS],
"capital": [tuple(s.split(" ", 1)) for s in CAPITALS],
"add": [(f"{a} + {b}", str(a + b)) for a, b in sorted(pairs)],
}
print("pool sizes:", {t: len(p) for t, p in POOL.items()})
# per task: instruction, demonstration format, query format
TASKS = {
"caps": ("Convert each word to upper case.", "{x} => {y}", "{x} =>"),
"capital": ("Name the capital of each country.", "{x} => {y}", "{x} =>"),
"add": ("Add the two numbers.", "{x} = {y}", "{x} ="),
}
def cols(cells, widths):
"""align by display width: first column left, the rest right
(a CJK character takes two cells)"""
def width(s):
return sum(2 if ord(c) > 0x2e80 else 1 for c in s)
out = " " + cells[0] + " " * (widths[0] - width(cells[0]))
for c, w in zip(cells[1:], widths[1:]):
out += " " * (w - width(c)) + c
return out
def make(task, draw):
"""per draw: 40 queries; 16 demonstrations per query, the first
k are used for k shots; queries and demonstrations use independent
seeds"""
pool = POOL[task]
queries = random.Random(f"{task}/query/{draw}").sample(pool, NQ)
out = []
for qi, q in enumerate(queries):
rest = [p for p in pool if p != q]
demos = random.Random(f"{task}/demo/{draw}/{qi}").sample(rest, 16)
out.append((demos, q, qi))
return out
def prompt(task, demos, q, k, shuffle=False):
"""shuffle rotates the answers of the first k demonstrations: same format,
wrong pairing"""
ins, fd, fq = TASKS[task]
demos = demos[:k]
if shuffle:
shift = random.Random(f"{task}/shuffle/{q[0]}").randrange(1, k)
demos = [(x, demos[(i + shift) % k][1])
for i, (x, _) in enumerate(demos)]
lines = [ins, ""] + [fd.format(x=x, y=y) for x, y in demos]
return "\n".join(lines + [fq.format(x=q[0])])
def generate(model, tok, prompts):
"""greedy, at most 6 new tokens, keep the first line"""
enc = tok(prompts, return_tensors="pt", padding=True).to(DEV)
with torch.no_grad():
out = model.generate(**enc, max_new_tokens=6, do_sample=False,
pad_token_id=tok.eos_token_id)
if DEV == "mps":
torch.mps.empty_cache()
texts = tok.batch_decode(out[:, enc.input_ids.shape[1]:],
skip_special_tokens=True)
return [t.split("\n")[0].strip() for t in texts]
def grade(line, gold):
"""strict: the line equals the answer; lenient: the answer opens the
line and no letter or digit follows"""
return line == gold, re.match(re.escape(gold) + r"(\W|$)", line) is not None
tok = AutoTokenizer.from_pretrained("gpt2")
tok.pad_token, tok.padding_side = tok.eos_token, "left"
strict, lenient, shuf, shown = {}, {}, {}, {}
for hub, name in MODELS:
model = GPT2LMHeadModel.from_pretrained(
hub, dtype=torch.float32, attn_implementation="eager")
model.to(DEV).eval()
if hub == "gpt2":
mix = [prompt(t, d, q, 8) for t in TASKS
for d, q, _ in make(t, 0)[:4]]
both = generate(model, tok, mix)
same = sum(generate(model, tok, [p])[0] == b for p, b in zip(mix, both))
print(f"padding check: batched and one-by-one greedy outputs match "
f"{same}/{len(mix)}")
for task in TASKS:
for draw in range(DRAWS):
items = make(task, draw)
for k in KS + (-SHUF_K,):
ps = [prompt(task, d, q, abs(k), k < 0) for d, q, _ in items]
lines = generate(model, tok, ps)
grades = [grade(ln, q[1])
for ln, (_, q, _) in zip(lines, items)]
cell = (hub, task, abs(k), draw)
if k < 0:
shuf[cell] = sum(g[0] for g in grades)
else:
strict[cell] = sum(g[0] for g in grades)
lenient[cell] = sum(g[1] for g in grades)
shown[cell] = [(q[1], ln) for ln, (_, q, _)
in zip(lines[:2], items[:2])]
del model
if DEV == "mps":
torch.mps.empty_cache()
def acc(table, hub, task, k):
return [100 * table[hub, task, k, d] / NQ for d in range(DRAWS)]
W = (14,) + (7,) * len(KS)
head = ("model",) + tuple(f"k={k}" if k == 0 else str(k) for k in KS)
spreads, gaps = [], []
for task, (ins, _, _) in TASKS.items():
print(f"\ntask {task}: {ins}")
print(f" strict accuracy (%), mean of {DRAWS} draws of {NQ} queries")
print(cols(head, W))
for hub, name in MODELS:
means = [sum(acc(strict, hub, task, k)) / DRAWS for k in KS]
print(cols((name,) + tuple(f"{m:.1f}" for m in means), W))
print(" spread across the draws (max - min, percentage points)")
for hub, name in MODELS:
row = []
for k in KS:
a = acc(strict, hub, task, k)
row.append(max(a) - min(a))
spreads.append(row[-1])
gaps.append((sum(acc(lenient, hub, task, k)) / DRAWS
- sum(acc(strict, hub, task, k)) / DRAWS,
name, task, k))
print(cols((name,) + tuple(f"{s:.1f}" for s in row), W))
spreads.sort()
print(f"\nspread: median {spreads[len(spreads) // 2]:.1f}, "
f"largest {spreads[-1]:.1f} percentage points")
g = max(gaps)
print(f"lenient grading adds at most {g[0]:.1f} points over strict "
f"({g[1]}, {g[2]}, k={g[3]})")
print(f"\ncontrol: {SHUF_K} demonstrations with the answers rotated "
f"(same format, wrong pairing)")
W2 = (14, 10, 9, 9)
print(cols(("model", "task", "right", "wrong"), W2))
for hub, name in MODELS:
for task in TASKS:
right = sum(acc(strict, hub, task, SHUF_K)) / DRAWS
wrong = sum(100 * shuf[hub, task, SHUF_K, d] / NQ
for d in range(DRAWS)) / DRAWS
print(cols((name, task, f"{right:.1f}", f"{wrong:.1f}"), W2))
print("\nexamples: GPT-2 xl, first two queries of the first draw "
"(gold -> output)")
for task in TASKS:
for k in (0, 16):
shots = ", ".join(f"{g!r} -> {o!r}" for g, o in
shown["gpt2-xl", task, k, 0])
print(f" {task:8s} k={k:<3d} {shots}")
First the accuracy. Each task has two tables: strict accuracy (the mean of 3 draws), and the spread between the three draws (maximum minus minimum, in percentage points), which is the scale of the noise:
pool sizes: {'caps': 60, 'capital': 50, 'add': 200}
padding check: batched and one-by-one greedy outputs match 12/12
task caps: Convert each word to upper case.
strict accuracy (%), mean of 3 draws of 40 queries
model k=0 1 2 4 8 16
GPT-2 small 0.0 25.0 52.5 62.5 59.2 61.7
GPT-2 medium 0.0 87.5 90.0 91.7 91.7 90.8
GPT-2 large 0.0 84.2 91.7 90.8 92.5 92.5
GPT-2 xl 0.0 92.5 92.5 91.7 91.7 90.8
spread across the draws (max - min, percentage points)
GPT-2 small 0.0 5.0 10.0 7.5 7.5 12.5
GPT-2 medium 0.0 5.0 5.0 2.5 7.5 7.5
GPT-2 large 0.0 10.0 7.5 7.5 5.0 5.0
GPT-2 xl 0.0 5.0 0.0 2.5 2.5 5.0
task capital: Name the capital of each country.
strict accuracy (%), mean of 3 draws of 40 queries
model k=0 1 2 4 8 16
GPT-2 small 0.8 51.7 61.7 61.7 55.8 60.0
GPT-2 medium 40.8 84.2 85.0 83.3 85.0 86.7
GPT-2 large 93.3 90.8 91.7 91.7 90.8 91.7
GPT-2 xl 65.8 90.8 92.5 92.5 94.2 92.5
spread across the draws (max - min, percentage points)
GPT-2 small 2.5 10.0 7.5 12.5 5.0 7.5
GPT-2 medium 2.5 7.5 12.5 15.0 15.0 2.5
GPT-2 large 2.5 7.5 2.5 2.5 7.5 5.0
GPT-2 xl 5.0 5.0 5.0 10.0 2.5 10.0
task add: Add the two numbers.
strict accuracy (%), mean of 3 draws of 40 queries
model k=0 1 2 4 8 16
GPT-2 small 0.0 0.8 0.8 0.0 1.7 1.7
GPT-2 medium 0.0 2.5 0.8 1.7 1.7 1.7
GPT-2 large 2.5 0.0 2.5 0.8 2.5 4.2
GPT-2 xl 4.2 3.3 3.3 1.7 1.7 4.2
spread across the draws (max - min, percentage points)
GPT-2 small 0.0 2.5 2.5 0.0 5.0 2.5
GPT-2 medium 0.0 7.5 2.5 2.5 2.5 2.5
GPT-2 large 0.0 0.0 5.0 2.5 5.0 2.5
GPT-2 xl 2.5 5.0 7.5 2.5 2.5 10.0
spread: median 5.0, largest 15.0 percentage points
lenient grading adds at most 0.8 points over strict (GPT-2 large, capital, k=1)
Number of examples: the biggest jump is from 0 to 1. In upper-casing, all four sizes score 0.0% at ; at small scores 25.0% and medium, large and xl score 87.5%, 84.2% and 92.5%. In the capital task gives 0.8%, 40.8%, 93.3% and 65.8%, and gives 51.7%, 84.2%, 90.8% and 90.8%. After that the curves are mostly flat: from to medium, large and xl all stay between 90.0% and 92.5% in upper-casing, a change no larger than the spread between the three draws (up to 7.5 points), so neither “more examples is better” nor “worse” can be read out. Small is slower: 25.0%, 52.5%, 62.5%, and from on it wanders between 59.2% and 62.5%.
Size. Small is furthest from the other three. At upper-casing gives 61.7%, 90.8%, 92.5% and 90.8%, so small is about 30 points below the rest, more than the spread between draws (at most 12.5); medium, large and xl differ by less than the spread and cannot be ranked. Capitals give 60.0%, 86.7%, 91.7% and 92.5%; medium is 5 to 6 points below large and xl, which is of the same order as the spread and is likewise not interpreted. The one thing that can be read out is a clear step from small to medium; the differences above that are too small to see.
Reading the replies: what kind of mistakes sit on the plateau. Is the plateau near 90% a formatting problem, a grading problem, or does the model really not know? The diagnostic script below runs the experiment above up to its model loop to get the same queries and prompts, reruns the and cells on the CPU, and sorts the mistakes into a few types. First, one check: the accuracies of all 16 cells of the CPU rerun are identical to the MPS table above (for example xl on upper-casing at is 90.8%, and on capitals at it is 65.8%), and lenient grading is at most 0.8 points above strict, so the strictness of grading is not the cause.
Diagnostic script (about 71 lines)
"""Reading the replies: what kind of mistakes GPT-2 makes at k=0 and k=16.
Runs the in-context-learning script up to its model loop to get the same
queries and prompts, then reruns those two cells on the CPU"""
import collections
import contextlib
import io
import sys
src = open("exp_gpt_icl_en.py", encoding="utf-8").read()
sys.argv = ["x", "cpu"]
with contextlib.redirect_stdout(io.StringIO()):
exec(compile(src[:src.index("tok = AutoTokenizer")], "exp", "exec"))
# torch and transformers are imported by the part executed above
tok = AutoTokenizer.from_pretrained("gpt2")
tok.pad_token, tok.padding_side = tok.eos_token, "left"
CITIES = {y for _, y in POOL["capital"]}
CHECKED = ("caps", "capital")
wrong = {}
for hub, name in MODELS:
model = GPT2LMHeadModel.from_pretrained(
hub, dtype=torch.float32, attn_implementation="eager")
for p in model.parameters():
# mmap-loaded weights can be misaligned on the CPU: copy them
p.data = p.data.clone()
model.eval()
probe = model(**tok("Hello", return_tensors="pt")).logits
assert torch.isfinite(probe).all()
for task in CHECKED:
for k in (0, 16):
bad = []
for draw in range(DRAWS):
items = make(task, draw)
lines = generate(model, tok, [prompt(task, d, q, k)
for d, q, _ in items])
bad += [(q[0], q[1], ln) for ln, (_, q, _)
in zip(lines, items) if ln != q[1]]
wrong[hub, task, k] = bad
del model
def kind(task, x, out):
"""the type of a mistake: copied the query, another country's
capital, upper case but another word; everything else counts as other"""
if out.strip("\"'").lower() == x.lower():
return "copied the query"
if task == "capital":
return "another country's capital" if out in CITIES else "other"
return "another word in capitals" if out.isupper() else "other"
total = DRAWS * NQ
print(f"CPU, {total} prompts per cell ({DRAWS} draws of {NQ} queries)")
for k in (0, 16):
print(f"\nk={k}")
for hub, name in MODELS:
for task in CHECKED:
bad = wrong[hub, task, k]
kinds = collections.Counter(kind(task, x, o) for x, _, o in bad)
words = len({x for x, _, _ in bad})
tail = ", ".join(f"{c} {v}" for c, v in sorted(kinds.items()))
print(f"{name:13s} {task:8s} wrong {len(bad):3d}/{total}"
f" (accuracy {100 - 100 * len(bad) / total:.1f}%), "
f"{words} distinct queries: " + tail)
print("\nAll mistakes of GPT-2 xl at k=16 (query, gold -> output, ×count)")
for task in CHECKED:
print(" ", task)
for (x, g, o), c in sorted(collections.Counter(
wrong["gpt2-xl", task, 16]).items()):
print(f" {x:12s} {g:10s} -> {o} ×{c}")
CPU, 120 prompts per cell (3 draws of 40 queries)
k=0
GPT-2 small caps wrong 120/120 (accuracy 0.0%), 60 distinct queries: copied the query 92, other 28
GPT-2 small capital wrong 119/120 (accuracy 0.8%), 49 distinct queries: copied the query 72, other 47
GPT-2 medium caps wrong 120/120 (accuracy 0.0%), 60 distinct queries: another word in capitals 1, copied the query 91, other 28
GPT-2 medium capital wrong 71/120 (accuracy 40.8%), 30 distinct queries: copied the query 68, other 3
GPT-2 large caps wrong 120/120 (accuracy 0.0%), 60 distinct queries: another word in capitals 3, copied the query 97, other 20
GPT-2 large capital wrong 8/120 (accuracy 93.3%), 3 distinct queries: copied the query 5, other 3
GPT-2 xl caps wrong 120/120 (accuracy 0.0%), 60 distinct queries: copied the query 99, other 21
GPT-2 xl capital wrong 41/120 (accuracy 65.8%), 18 distinct queries: copied the query 16, other 25
k=16
GPT-2 small caps wrong 46/120 (accuracy 61.7%), 28 distinct queries: another word in capitals 42, copied the query 4
GPT-2 small capital wrong 48/120 (accuracy 60.0%), 28 distinct queries: another country's capital 34, other 14
GPT-2 medium caps wrong 11/120 (accuracy 90.8%), 7 distinct queries: another word in capitals 11
GPT-2 medium capital wrong 16/120 (accuracy 86.7%), 9 distinct queries: another country's capital 2, other 14
GPT-2 large caps wrong 9/120 (accuracy 92.5%), 6 distinct queries: another word in capitals 7, copied the query 2
GPT-2 large capital wrong 10/120 (accuracy 91.7%), 5 distinct queries: other 10
GPT-2 xl caps wrong 11/120 (accuracy 90.8%), 6 distinct queries: another word in capitals 11
GPT-2 xl capital wrong 9/120 (accuracy 92.5%), 7 distinct queries: other 9
All mistakes of GPT-2 xl at k=16 (query, gold -> output, ×count)
caps
basket BASKET -> BAG ×1
guitar GUITAR -> GIRL ×1
guitar GUITAR -> GUN ×1
insect INSECT -> INSECTS ×2
kettle KETTLE -> KETCHEL ×1
lantern LANTERN -> LANGLER ×1
lantern LANTERN -> LUNAR ×1
parrot PARROT -> PAROON ×1
parrot PARROT -> PARROOT ×2
capital
Australia Canberra -> Melbourne ×1
Canada Ottawa -> Toronto ×1
India New Delhi -> Mumbai ×1
Libya Tripoli -> Benghazi ×2
Spain Madrid -> Barcelona ×1
Switzerland Bern -> Zurich ×2
Turkey Ankara -> Istanbul ×1
Three findings:
- The mistakes on the plateau are the model’s limits, not formatting. On capitals at , xl makes 9 mistakes, all on 7 countries, and every output is another big city in the same country (Melbourne, Toronto, Mumbai, Benghazi, Barcelona, Zurich, Istanbul), neither another country’s capital nor a format error. On upper-casing it makes 11 mistakes on 6 words; the outputs are near copies with spelling slips (KETCHEL, LANGLER, PAROON, PARROOT), a plural (INSECTS) or a different word (BAG, GIRL, GUN, LUNAR). Small makes 48 mistakes on capitals, 34 of them another country’s capital: it has learned the format “answer with a capital” but not which one.
- Zero-shot differences are mostly about whether the answer gets written at all. In upper-casing at none of the 120 prompts is answered correctly at any size, and the reply copies the query word back (ignoring quotes and case) in 92, 91, 97 and 99 of them, which says that without examples GPT-2 does not act on an instruction like “Convert each word to upper case.” The capital task at is more telling: medium makes 71 mistakes, 68 of which copy the country name back rather than naming a wrong city, and large makes only 8. The zero-shot scores of the four sizes (0.8%, 40.8%, 93.3%, 65.8%) are not monotonic in size, which looks like “knowing the answer” and “writing the answer in the right format” mixed together; with one example, medium reaches 84.2%.
- What small has learned is the format. For small at , 42 of its 46 upper-casing mistakes are a different word written in capitals and only 4 are unconverted (see the output above), which fits “the format learned, the content not”.
Does the pairing matter? After rotating the answers of the examples, accuracy looks like this (“pairing right” is the column of the tables above):
control: 8 demonstrations with the answers rotated (same format, wrong pairing)
model task right wrong
GPT-2 small caps 59.2 22.5
GPT-2 small capital 55.8 49.2
GPT-2 small add 1.7 0.0
GPT-2 medium caps 91.7 30.8
GPT-2 medium capital 85.0 75.0
GPT-2 medium add 1.7 0.8
GPT-2 large caps 92.5 55.8
GPT-2 large capital 90.8 77.5
GPT-2 large add 2.5 0.8
GPT-2 xl caps 91.7 35.0
GPT-2 xl capital 94.2 69.2
GPT-2 xl add 1.7 0.8
Upper-casing drops the most: xl from 91.7% to 35.0%, large from 92.5% to 55.8%, which says the model follows the pairing shown in the examples and writes what the wrong pairing implies. Capitals drop less: xl from 94.2% to 69.2%, large from 90.8% to 77.5%, medium from 85.0% to 75.0% and small from 55.8% to 49.2%. The three larger sizes still get about seven in ten right, because the answer comes mostly from knowledge in the weights and the examples mostly supply the format; but the drops of xl and large exceed their own spread at , so the pairing matters too, while the drops of medium and small are of the same order as the noise. Two-digit addition is near zero anyway, and both columns stay at or below 2.5%. In other words it is neither “only the format matters” nor “everything is the pairing”; the balance depends on the task. When the model already knows the answer the examples mostly set the format; when the examples have to define the answer, the pairing decides.
This does not conflict with Min et al. (2022), who found on classification and multiple-choice tasks that randomly replacing the labels in the demonstrations barely hurts, and that what the demonstrations mainly provide is the label space, the distribution of the input text and the format of the sequence. The tasks here are generative with an open answer space, and the change is a rotation rather than random replacement, so this is not a test of that paper; it only shows that whether the pairing matters depends on the task.
Two-digit addition. No size and no goes above 4.2%, so GPT-2 cannot do this. The GPT-3 paper reports 100% for few-shot two-digit addition at 175B and about half for 13B; but its prompts are natural-language questions (Q: What is 48 plus 76? A: 124.) with numbers from 0 to 100, unlike the a + b = form and 10 to 99 here, so the numbers cannot be compared directly. All one can say is that the task is near zero at GPT-2 scale and shows up only at larger scales.
Finally, a few examples (GPT-2 xl, the first two queries of the first draw):
examples: GPT-2 xl, first two queries of the first draw (gold -> output)
caps k=0 'MOUNTAIN' -> 'mountain', 'ENGINE' -> '"engine"'
caps k=16 'MOUNTAIN' -> 'MOUNTAIN', 'ENGINE' -> 'ENGINE'
capital k=0 'Bern' -> 'Zürich', 'Paris' -> 'Paris'
capital k=16 'Bern' -> 'Zurich', 'Paris' -> 'Paris'
add k=0 '57' -> '55', '120' -> ''
add k=16 '57' -> '56', '120' -> '122'
What to take away and what not to. Three things can be taken away: what the examples teach first is the format, and one example gives a big jump; the examples give both the format and the pairing, in proportions that depend on the task; and size differences are largest over the first few examples, after which each size stays on its own plateau. What cannot be taken away must be just as clear: the tasks are three self-made toys; only the four GPT-2 sizes were run, which cannot speak for GPT-3; the task description and format were each written once and never ablated; each cell has only 120 prompts and the median spread between draws is 5.0 points, so differences smaller than that should not be interpreted; and goes only up to 16, with longer contexts untested.
Limits and what came after
- The training-data leakage problem was not fully solved. Section 4 of the GPT-3 paper says the authors tried to find and remove all overlaps between the training data and every benchmark’s development and test sets, but a bug removed only some of them, and the cost of training made retraining infeasible; so the paper builds a “clean” subset for each benchmark and compares the score on it with the full score. Most benchmarks changed little and a few were flagged as possibly contaminated. This is an early case of the benchmark contamination problem discussed in the evaluation material.
- Undertrained allocation. The 1.72 tokens per parameter above; after Chinchilla the field spends the same compute more on tokens (see the Chinchilla note).
- It continues text, but does not necessarily obey. Few-shot prompting teaches a model that only continues text; getting it to follow instructions directly takes instruction tuning and preference optimization (see the InstructGPT note).
- Safety and release. GPT-2 was released in stages, and the model card discusses bias and possible misuse and advises deployers to run a study of biases relevant to the intended use case first (the model card and repository are linked at the end).
- How to read these papers. All three are OpenAI technical reports or papers without public training code or data; the experiments on this page use only the public GPT-2 checkpoints, so they speak for GPT-2’s scale curve and not for GPT-3.
What to take away from the three papers
- One network, three interfaces. The pre-training objective did not change; what changed is where the task enters the model: in the weights (fine-tuning), in the text (zero-shot), or in examples in the context (few-shot).
- Scale is what made the interface work. GPT-2’s abstract calls capacity the key to zero-shot transfer, and GPT-3’s curves show larger models making better use of the examples in the context.
- Parameter counts follow from a formula; do not copy the paper’s table. The paper’s 117M and 345M are nominal values for “equivalent to GPT and BERT”; the real values are 124M and 355M, and the 137M on the Hugging Face page also includes mask buffers.
- GPT-3’s design is Kaplan’s scaling law. Table D.1 gives 1.72 tokens per parameter, the reason Chinchilla later corrected it.
- A paper’s own tables can disagree with themselves. The 5140 of the 13B model, the heads of XL and the epochs of WebText2 can each be found in a few lines of code; read papers with a calculator.
Further reading
- Papers: Improving Language Understanding by Generative Pre-Training (GPT-1); Language Models are Unsupervised Multitask Learners (GPT-2); Language Models are Few-Shot Learners (GPT-3).
- Official material: the openai/gpt-2 repository (including the correction of the parameter counts) and the model card.
- Before, after and for comparison: Scaling Laws for Neural Language Models; Training Compute-Optimal Large Language Models (Chinchilla); Training language models to follow instructions with human feedback (InstructGPT); BERT; Attention Is All You Need.
- On this site: Training Pipeline, Scaling Laws, Prompt Engineering, Next-Token Prediction, the Scaling Laws note, the Chinchilla note, the InstructGPT note and the BERT note.
FAQ
- What is the difference between GPT-1, GPT-2 and GPT-3?
- They are three scale-ups of one decoder-only Transformer recipe; what differs is the size and how a task reaches the model. GPT-1 (2018) has 12 layers, about 117 million parameters and a 512-token context, and is pre-trained on BooksCorpus and then fine-tuned for each task. GPT-2 (2019) goes up to 48 layers, 1,557,611,200 parameters and a 1024-token context, is trained on WebText, and is used zero-shot with the task written as text. GPT-3 (2020) goes up to 96 layers, about 174.6 billion parameters (the paper prints 175B) and a 2048-token context, is trained on 300 billion tokens, and does zero-shot, one-shot and few-shot learning from instructions and examples in the context.
- How many parameters does GPT-2 really have? Are 117M, 345M, 762M and 1542M correct?
- No. Counting from the block structure gives 124,439,808, 354,823,168, 774,030,080 and 1,557,611,200, and the formula, the Hugging Face model classes and the checkpoint files agree exactly. Table 2 of the paper prints numbers that are 6.4%, 2.8%, 1.6% and 1.0% too small. OpenAI's own GitHub repository admits that the original counts were wrong, and its model card lists 124M, 355M, 774M and 1.5 billion. The 117M label is really the size of GPT-1 (116,534,784 by this page's count).
- What is in-context learning, and how does it differ from fine-tuning?
- In-context learning puts the task description or a few input-output examples directly in the prompt; the weights are never updated and the model picks up the task during the forward pass. Fine-tuning updates the weights with task data and produces a new set of weights per task, while in-context learning adapts at inference time and one set of weights serves every task. The GPT-3 paper separates zero-shot (a description only), one-shot (one example) and few-shot (typically 10 to 100 examples, limited by the 2048-token context). This page measures it on the four GPT-2 sizes: in upper-casing, going from 0 to 1 examples lifts accuracy from 0.0% to between 25.0% (small) and 92.5% (xl), and it is then mostly flat; rotating the answers in the examples cuts upper-casing sharply (xl from 91.7% to 35.0%), so the examples carry more than the format.
- Was GPT-3 undertrained on only 300 billion tokens?
- By later standards, yes. Recomputing Table D.1 shows the 175B model sees only 1.72 tokens per parameter, against 23.35 for the 13B model. The caption of Figure 2.2 says the paper followed the analysis of Kaplan et al. and trained much larger models on many fewer tokens than is typical. Chinchilla (Hoffmann et al., 2022) found that this split is undertrained: a 70-billion-parameter model on 1.4 trillion tokens, about 20 tokens per parameter, did better than Gopher at the same compute.
- Are there errors in the tables of the GPT-3 paper?
- A few places do not agree with themselves. In Table 2.1 the 13B model's d_model is printed as 5140 while heads times head size is 5120, and with 5120 the formula matches Table D.1's parameter count to within 0.03%. The XL model has 24 heads of size 128, which is 3072, against a d_model of 2048. In Table 2.2 WebText2 is printed at 2.9 epochs but recomputes to 3.47 from its token count and mixture weight (the weight counts examples, not tokens, so this is not necessarily an error), and the five weights add up to 101%. The text gives 80.2% for few-shot three-digit addition while Table 3.9 prints 80.4%. Table D.1's FLOPs and petaflop/s-days are self-consistent to within 0.21%.