GPT-2 Paper Notes Transformers Zero-shot Language Modeling

The takeaway first

TL;DR

GPT-1 showed that pretraining (training on large number of books) a language model and then fine-tuning it works across many tasks. GPT-2 asks whether a much larger model, trained on a much broader corpus, can begin to do those tasks without any task-specific fine-tuning.

GPT-1 · 2018

Pretrain → fine-tune → High Performing Outcome

Generative Pre Training of language model on diverse unlabeled text improves performance of fine-tuned models on task specific functions

GPT-2 · 2019

Pretrain → High Performing Outcome

Natural Langauge Processing tasks can be learned without any explicit supervision during the pre-training stage using large amount of data from web

The paper's central bet: broad web text + next-token prediction + scale can produce useful zero-shot behavior on tasks the model was never trained for.

Don't train a model for each task.
Train one model on enough text that the tasks are already in it.
1.5B
parameters in the largest model
7 / 8
LM benchmarks at zero-shot state of the art
~40 GB
of web text in WebText
0
task-specific fine-tuning runs

Motivation

From narrow task models to one general language model

NLP systems of the time were built around one labeled dataset and one objective. They did very well on test sets drawn from the same distribution, and broke easily outside it. The authors call these systems "narrow experts", and they are clear about where they think the brittleness comes from:

"Our suspicion is that the prevalence of single task training on single domain datasets is a major contributor to the lack of generalization observed in current systems."

If narrow training is what hurts generalization, the fix is to train broadly. GPT-2 starts from that ambition: one model should learn enough about language that many tasks can be expressed directly through text, with no dedicated finetuning.

The key observation is that the internet already contains natural demonstrations of many tasks: translation pairs, questions and answers, summaries, definitions and explanations. A model trained only to predict the next token still benefits from learning these patterns, because doing so lowers its loss. A single-task system only learns to map an input to an output. A general system also has to know which task it is being asked to do, and GPT-2's bet is that the task can simply be described in text.

GLUE vs DecaNLP

The paper positions itself against two multitask benchmarks of the time.

Benchmark suite

GLUE

A shared set of language-understanding tasks such as entailment, paraphrase detection, acceptability and similarity. Each task keeps its own native format.

Unified format

DecaNLP

Goes further by casting ten different NLP tasks into one question-answering, text-to-text interface.

Glossary
Entailment
Does sentence A imply sentence B?
Paraphrase detection
Do two sentences mean the same thing?
Acceptability
Is this sentence grammatical?
Similarity
How close in meaning are two sentences?

Training data

WebText: a deliberately broad corpus

GPT-1 read 7000 books. For GPT-2 the authors went ahead with web pages which contains long contiguous text across domains. They built WebText, a new corpus: the pages behind outbound Reddit links that received at least 3 karma. Reddit votes act as a rough human quality filter. Links that people chose to share and upvote are more likely to hold useful or interesting text. Wikipedia was removed on purpose to avoid overlapping with evaluation datasets.

WebText uses social curation as a filter, then keeps the text behind those links.

Cleaning text with Dragnet and Newspaper

They are web page content extractors. Dragnet extracts article main content and Newspaper also helps with article text along with metadata.

Input representation

Why GPT-2 moved to byte-level BPE

A general language model should be able to assign a probability to any string. And the NLP techniques often used preprocessing steps like lowercasing and stemming, restricting the space of modelable strings. Playing with UNICODE representation of characters was an elegant way to handle this as it contains ~150K characters and can represent any language. However, character level encoding is inefficient. Modeling raw bytes avoids the problem, since every Unicode string can be encoded with only 256 possible byte values, but byte sequences are long and slow to model.

GPT-2 keeps GPT-1's core idea, BPE, but changes what it runs on. GPT-1 cleaned its text with ftfy, split it into words with the spaCy tokenizer, and learned 40,000 merges starting from characters, so a character it never saw in training had no symbol at all. GPT-2 drops the cleanup and the English-specific pre-tokenizer, and runs BPE directly on raw UTF-8 bytes. Any string can now be encoded, and 50,000 merges give a vocabulary of 50,257 tokens (256 bytes + 50,000 merges + 1 end-of-text token). The one rule it adds is that BPE can't merge across character categories, so dog., dog! and dog? don't each take up a vocabulary slot.

Why bytes win Unicode has over 1.1 million possible code points, about 150K of them assigned. Bytes have 256. An emoji like 😀 is code point 128,512, but in UTF-8 it is just four bytes, 240 159 152 128, and BPE can merge those back into a single token if it shows up often enough.

Go deeper

Building Your Own GPT-2 Tokenizer from Scratch

Byte-pair encoding over UTF-8, step by step: count pairs, merge, repeat, and train the GPT-2 tokenizer yourself on Shakespeare.

Glossary
BPE
Byte Pair Encoding: repeatedly glue together the pair of symbols that appears most often, until common chunks become single units.
Merge
One BPE step: replace every occurrence of a frequent pair of symbols with a single new symbol.
UTF-8
The most common way to write characters as bytes. English letters take 1 byte, emoji take 4.
ftfy
"Fixes text for you": a library that repairs broken Unicode and normalizes punctuation.
spaCy
A popular open-source NLP library. Its tokenizer splits text into words and punctuation.
Character category
Unicode's grouping of characters into letters, digits, punctuation, symbols and so on.

Architecture

GPT-1's architecture, scaled and stabilized

There is no new architecture here. GPT-2 keeps the decoder-only Transformer from GPT-1 and makes a few changes:

  • Layer norm moves to the input of each sub-block, and one extra layer norm is added after the final block.
  • Initialization changes to stay stable as the stack gets deeper.
  • The context window doubles from 512 to 1,024 tokens.
  • Batch size grows to 512.
Model Layers Heads dmodel Released size
GPT-2 Small 12 12 768 124M
GPT-2 Medium 24 16 1024 355M
GPT-2 Large 36 20 1280 774M
GPT-2 XL 48 25 1600 1.558B

Every size keeps the same head width:

$$d_{\text{head}} = \frac{d_{\text{model}}}{n_{\text{heads}}} = \frac{768}{12} = \frac{1600}{25} = 64$$
A correction to Table 2 The parameter counts printed in the paper, 117M, 345M, 762M and 1542M, are not the sizes of the released models. The layer, head and width columns are right. Only the parameter column is off, and the table above uses the corrected numbers.

BEFORE BENCHMARKING

A nuance before benchmarking

Before the results, the paper explains how it evaluates GPT-2 on existing language-modeling benchmarks. GPT-2 is still predicting the next token, just on datasets it was never trained on. Two problems come up straight away: every benchmark reports its score in its own unit, and many benchmarks have been preprocessed in ways that look nothing like the web text GPT-2 learned from. The paper puts it like this:

What the paper says

"Results on language modeling datasets are commonly reported in a quantity which is a scaled or exponentiated version of the average negative log probability per canonical prediction unit, usually a character, a byte, or a word."

"For many of these datasets, WebText LMs would be tested significantly out-of-distribution, having to predict aggressively standardized text, tokenization artifacts such as disconnected punctuation and contractions, shuffled sentences, and even the string <UNK> […] We report our main results using invertible de-tokenizers which remove as many of these tokenization / pre-processing artifacts as possible."

Canonical prediction unit: the benchmark's official unit

GPT-2 splits text into its own BPE tokens, other models split it into words or characters, so "loss per token" means something different for each model. To compare them, every benchmark fixes one official unit (its canonical unit) and everyone divides by that, whatever their tokenizer does internally.

So GPT-2 computes the total log-probability of the whole test set, then divides by the number of canonical units in it:

$$\text{average loss} = \frac{-\log p(\text{dataset})}{N}$$
\(N\)
the number of canonical units (words, characters or bytes) in the benchmark

For example, if a word-level benchmark contains the sentence the cat sat, GPT-2 might spend four BPE tokens on it, but \(N\) is still 3 words. Perplexity is then derived from this per-word loss. Because the denominator is fixed by the benchmark, models with completely different tokenizers can be compared fairly.

Invertible de-tokenizer: undo the benchmark's preprocessing

Many older benchmarks were tokenized before release, with punctuation and contractions split off by spaces:

Tokenized benchmark → natural text
Idon'tlikeit. → I don't like it.

GPT-2 almost never saw text like that on the web. Some benchmarks even replace rare words with the literal string <UNK>, which appears only 26 times in 40 billion bytes of WebText. The model ends up penalized for not predicting formatting quirks rather than language.

A de-tokenizer is a small script that turns the benchmark text back into natural text. It has to be invertible: there must be an exact, one-to-one way back to the original benchmark format. That way GPT-2 reads natural text, but the probability can still be counted against the official benchmark text and its canonical units, so the score stays comparable. The paper calls this a simple form of domain adaptation, and reports 2.5 to 5 perplexity points of improvement from it.

Result Without seeing a single training example from these datasets, the largest GPT-2 reaches state of the art on 7 of 8 language-modeling benchmarks. The exception is One Billion Word, whose sentence-level shuffling destroys the long-range structure GPT-2 is good at.
Glossary
Negative log-likelihood
How surprised the model is by the real text; lower is better.
Perplexity
Roughly, how many options the model is torn between at each step; lower is better.
Canonical prediction unit
The official unit a benchmark divides its loss by (word, character or byte), whatever the model's own tokenizer.
Invertible de-tokenizer
A script that undoes a benchmark's odd spacing in a way that can be reversed exactly.
Domain adaptation
Adjusting for the gap between the kind of data a model was trained on and the kind it is tested on.

Experiments · Zero-shot results

Insights from benchmarking

GPT-2 was tested on 8 language-modeling datasets and 5 kinds of downstream task.

Language modeling: how much better than the previous best?

Relative reduction in perplexity (PPL) or bits per character/byte (BPC/BPB) for the 1.5B model versus the previous best. Lower raw scores are better on all of these. Gains are largest where earlier models had the least data or the longest context, and negative on One Billion Word.

  • Small datasets gain most. Penn Treebank and WikiText-2 have only 1 to 2 million training tokens, so models trained on them alone had little to learn from. GPT-2 arrives with 40 GB of prior reading.
  • One Billion Word goes backwards. Uses destructive preprocessing where sentences are shuffled, which destroys the long-range structure GPT-2 relies on, and it is the largest dataset of the eight.

Downstream tasks: GPT-2 zero-shot vs the reference

GPT-2, zero-shotreference system
Beats the previous best
Far behind supervised or specialist systems

All scores on a 0–100 scale, but each task has its own metric, so compare bars within a row, not across rows. The split is the story: tasks that look like next-word prediction are won, tasks that need knowledge or long generation are not.

Benchmark by benchmark

LAMBADA8.63 PPL · 63.24%

Predict the last word of a passage, where a human needs the whole passage, not just the last sentence, to guess it.

InferencePerplexity falls from 99.8 to 8.63 and accuracy beats the previous best. GPT-2 really does use long-range context.

Why it makes senseEarlier models were trained on LAMBADA's own small novel corpus and struggled to carry information far back. GPT-2 has a 1,024-token window and 40 GB of practice. Unfiltered accuracy is only 52.66% because many wrong guesses were valid continuations of the sentence, not valid final words; a stop-word filter lifts it to 63.24%.

Children's Book Test93.3% · 89.05%

Pick the missing word in a passage from 10 candidates, scored separately for common nouns and named entities.

InferenceBeats the previous best on both, with accuracy still climbing as the model grows.

Why it makes senseA cloze test is next-word prediction with a multiple-choice sheet, exactly what GPT-2 is trained to do. One test-set book, The Jungle Book, is in WebText, so the paper reports the validation set instead.

Decide what a pronoun refers to in a sentence that needs commonsense, like which object was "too big" to fit.

InferenceAbout 7 points above the previous best.

Why it makes senseEach option can be scored as "which full sentence is more likely?", which is again language modeling. With only 273 examples, a few questions move the score a lot, so treat the margin with care.

CoQA55 F1

Answer a chain of conversational questions about a document.

InferenceMatches or beats 3 of 4 baseline systems without any of their 127,000+ training examples, but is far below the ~89 F1 of humans.

Why it makes senseThe paper notes GPT-2 often leans on simple tricks, such as answering a "who" question with a name from the document. Reading comprehension needs more than surface patterns, so the gap to supervised systems is expected.

CNN/Daily Mail21.40 ROUGE

Summarize a news article; GPT-2 is prompted by adding TL;DR: after it.

InferenceBarely beats picking 3 random sentences (20.98) and trails simply copying the first 3 (Lead-3, 31.55). Removing TL;DR: drops it to 15.03.

Why it makes senseNews puts the key facts first, so Lead-3 is very hard to beat on word overlap. GPT-2 writes freely, often focuses on the end of the article and mixes up details, and ROUGE punishes every word that differs. The 6-point drop without the hint shows the prompt is read as a task.

Translate sentences, prompted with example pairs in the form english = french.

InferenceEnglish→French is weak at 5 BLEU; French→English reaches 11.5, far behind the best unsupervised system at 33.5.

Why it makes senseOnly about 10 MB of WebText was French, roughly 0.025% of the corpus. Reading French and writing English uses GPT-2's strong English model; writing French does not. Any translation at all from so little data is the surprise.

Natural Questions4.1% exact match

Answer real Google search questions from memory, with no document to read.

InferenceLow overall, but 63.1% correct on the 1% of questions it is most confident about, and 5.3× more correct answers than the smallest GPT-2.

Why it makes senseEvery fact has to be stored in 1.5B parameters. Dedicated open-domain systems that search documents score 30–50%. The smallest model does not even beat the 1.0% of a baseline that returns the most common answer per question type, so knowledge clearly grows with size.

Glossary
BPC / BPB
Bits per character / per byte: perplexity's cousin for character-level benchmarks; lower is better.
Cloze task
Fill in the blank.
Pronoun resolution
Working out who or what words like “it” or “they” refer to.
Stop words
Very common words like “the”, “and” or “of”.
F1
A 0 to 100 score of how much the answer's words overlap with the correct answer.
ROUGE
A score of word overlap with a human-written summary.
Lead-3
A baseline that copies the first three sentences of the article.
BLEU
A 0 to 100 score of how closely the output matches human translations.
Exact match
The answer counts only if it matches the correct one exactly.
Open-domain QA
Answering questions on any topic, usually by searching documents first.

Generalization vs memorization

Did GPT-2 just see the test set?

A zero-shot result can be contaminated if the test examples were already in the training data. With 40 GB of web text, that is a fair worry. The authors check overlap between WebText and public benchmarks using a Bloom filter over normalized 8-grams.

Bloom filters trade exact storage for compact, probabilistic lookup. They can give false positives, never false negatives.

How would you build one?

Normalize the training text, cut it into 8-word shingles (overlapping chunks), hash each shingle into the filter, then query the evaluation shingles with the same normalization.

minimal concept · python
from pybloom_live import BloomFilter

bf = BloomFilter(capacity=10_000_000, error_rate=0.001)

def ngrams(text, n=8):
    words = text.lower().split()
    return [" ".join(words[i:i+n])
            for i in range(len(words)-n+1)]

for gram in ngrams(training_text):
    bf.add(gram)

"We generated 1M strings, of which zero were found by the filter"

This is a sanity check for false positives. Query the filter with a million strings that should not be in it. Any hit would be a false positive, and they saw none. That does not prove the true rate is zero, only that it is very low.

Why 8-grams? My reading The paper states the choice of 8-grams but gives no ablation or explicit reason for it. A reasonable interpretation is that eight words are long enough to avoid accidental matches on common phrases, and short enough to still catch copied passages.

Table 6: how much of each test set is already in training data?

For six of the language-modeling benchmarks, the paper cuts every test set into 8-grams and checks what percentage of them also appear in a training set. Each column is a benchmark's test set. Each row is the training set it is checked against: the benchmark's own training split, or WebText.

Checked against PTB WikiText-2 enwik8 text8 WikiText-103 1BW
Dataset train 2.67% 0.66% 7.50% 2.34% 9.09% 13.19%
WebText train 0.88% 1.63% 6.31% 3.94% 2.42% 3.75%

Why are there two rows in Table 6?

The WebText row on its own is hard to judge. Is 3.94% overlap on text8 a lot? The first row gives the answer by providing a baseline: how much a benchmark's test set already overlaps with its own training split. That overlap is normal and accepted, because test and training splits come from the same source and share common phrases, names and boilerplate.

So the real question is whether WebText overlaps with the test sets more than their own training data does. On average it does not: about 3.2% for WebText versus 5.9% for the benchmarks' own training splits. WebText is higher on only two datasets, WikiText-2 and text8, and even there the overlap is a few percent.

Average overlap with test sets. WebText overlap exists, but it is smaller than the overlap already present inside the benchmarks themselves.

Wrapping up

My Learnings

The key lesson GPT-2 is still a weak zero-shot model on most tasks. What it proved is the direction: every curve in the paper goes up with size, and none of them had flattened yet. GPT-3 is what happened when OpenAI followed those curves.

Related reading

GPT-1: The Beginning of ChatGPT Revolution

The pretrain-then-fine-tune recipe that GPT-2 set out to simplify.