AI Logic

Architectures

GPT-2

Updated:

Structure of GPT-2. Left: the overall flow (a sequence of byte-level BPE tokens, token and position embeddings, repeated decoder layers, a final layer normalization, next-token prediction) and the range of attention, which can see only positions to the left. Right: the inside of a decoder layer (masked self-attention and feed-forward in the Pre-LN form, with layer normalization on the input side)

Background and overview

GPT-2 is a language model that scales the same "decoder-only Transformer" as GPT up to 1.5 billion parameters and is trained only on next-word prediction over text from about 8 million web pages (WebText). It was presented by Radford et al. at OpenAI in 2019 in the technical report "Language Models are Unsupervised Multitask Learners."

GPT was fine-tuned on labeled data for each task after pre-training. The GPT-2 paper examined the next step beyond that.

  • If a sufficiently large language model is trained on sufficiently diverse text, might it be able to handle tasks such as reading comprehension, summarization, translation, and question answering to some degree without fine-tuning, simply by being instructed in the input text?

The paper calls this setting, in which a task is solved without training on a single example of it, zero-shot. As a result, GPT-2 achieved state-of-the-art results at the time zero-shot on 7 of 8 language modeling datasets. On conversational reading comprehension (CoQA), it achieved an F1 of 55, matching or exceeding 3 of the 4 baseline systems that used over 127,000 training examples.

On the other hand, its summarization and translation performance was still far from that of supervised methods, and the paper itself says it is "far from useful" in practice. Even so, the performance on every task kept rising log-linearly as the model grew (by a roughly constant amount for every tenfold increase in parameters), and even the largest model still underfit WebText. These results led to the later GPT-3.

Architecture: changes from GPT

The architecture of GPT-2 is almost the same as that of GPT. The left side of the figure at the top of the article shows the overall flow and the range attention can see, and the right side shows the inside of one decoder layer. The changes from GPT are as follows.

  1. Layer normalization is moved to the input of each sublayer (Pre-LN). This follows the same idea as the improved version of ResNet (the pre-activation form, with activation before the residual addition). For details, see Pre-LN and Post-LN.
  2. An extra layer normalization is added after the last layer, because with Pre-LN the output of the last layer is not normalized.
  3. The weights of the residual paths are scaled by 1/N1/\sqrt{N} at initialization (NN is the number of residual layers). This counteracts the accumulation of values along the residual path as the network gets deeper.
  4. The vocabulary is expanded to 50,257. Tokenization is byte-level BPE (explained below).
  5. The context length is increased from 512 to 1024 tokens, and the batch size is set to 512.

The computation of a Pre-LN sublayer is expressed by the following formula (xx is the input to the sublayer).

x←x+Sublayer(LayerNorm(x))x \leftarrow x + \mathrm{Sublayer}\bigl(\mathrm{LayerNorm}(x)\bigr)

Unlike GPT (Post-LN), LayerNorm(x+Sublayer(x))\mathrm{LayerNorm}(x + \mathrm{Sublayer}(x)), the input xx is added directly to the next layer without passing through normalization.

The paper trained four models of different sizes.

ParametersLayersVector length dmodeld_{\text{model}}Notes
117M12768Same size as the original GPT
345M241024Same size as BERT-Large
762M361280
1542M481600GPT-2 (more than 10 times GPT)

Byte-level BPE: to obtain a language model that can assign a probability to any string, text is treated as a sequence of UTF-8 bytes.

  • With BPE over Unicode characters, the base vocabulary alone exceeds 130,000. With bytes, the base vocabulary is only 256.
  • However, applying BPE directly to byte sequences creates separate tokens for forms of the same word with punctuation attached, such as "dog", "dog.", "dog!", and "dog?", wasting vocabulary. So merges across character categories (letters, punctuation, etc.) were prohibited (with an exception for spaces).

As a result, no preprocessing or unknown-word symbol (<UNK>) is needed, and the model can be evaluated on any dataset as is (byte-level tokenization).

Training: WebText and zero-shot instruction by text

GPT-2 is trained only as a language model. A text xx is regarded as a sequence of symbols (s1,…,sn)(s_1, \dots, s_n), and the following probability is maximized.

p(x)=∏i=1np(si∣s1,…,siβˆ’1)p(x) = \prod_{i=1}^{n} p(s_i \mid s_1, \dots, s_{i-1})

The training data (WebText) was newly collected with an emphasis on quality.

  1. Pages linked from posts with at least 3 karma (posts that received a certain level of approval from other users) on the social media site Reddit were collected. This is a shortcut for selecting only pages that people judged "interesting or useful."
  2. Text was extracted from 45 million links, and after deduplication and other cleaning, the result was slightly over 8 million documents (40 GB of text).
  3. Wikipedia documents, which tend to overlap with other datasets, were removed.

The learning rate of each model was tuned by hand for the best perplexity on a 5% held-out portion of WebText.

Instructing tasks in text: solving a task means estimating a conditional probability p(output∣input)p(\text{output} \mid \text{input}). To solve many tasks with one model, the task itself must also be included in the condition, estimating p(output∣input,task)p(\text{output} \mid \text{input}, \text{task}). In language, the task, input, and output can all be written as a single string. For example, translation can be expressed as the sequence "(translate to French, English text, French text)." The paper had the model generate answers without fine-tuning, using inputs like the following for each task.

TaskHow the input is builtHow the answer is produced
SummarizationAppend "TL;DR:" after the articleGenerate 100 tokens with top-k sampling (k=2k = 2) and use the first 3 sentences
Translation (En→Fr)List several "English sentence = French sentence" examples and end with "English sentence ="Use the first sentence generated with greedy decoding
Reading comprehension (CoQA)Place the document, the conversation so far, and finally "A:"Generate with greedy decoding
Fill-in-the-blank (CBT, Winograd)Build a sentence with each choice filled inChoose the one with the highest language model probability

"TL;DR:" is a stock phrase in English online posts that precedes a "summary for people who found it too long to read." Since WebText naturally contains text in this form, the language model has learned the pattern "a summary comes after TL;DR:." In the paper, removing this hint lowered the average ROUGE for summarization by 6.4 points.

Why tasks can be solved just by instruction

The paper's idea is that web text naturally contains "demonstrations" of tasks.

For example, WebText contains many cases where English and French translations appear within a sentence, such as "In French, 'Je ne suis pas un imbecile,' which means 'I'm not a fool.'" The paper argues that, in order to correctly predict the next word in such texts, the language model learns to infer and perform tasks such as translation. If so, training a language model amounts to "unsupervised multitask learning" in which tasks are never stated explicitly.

In theory as well, the supervised objective (predicting the output part) is the language modeling objective (predicting every position) evaluated on only part of the sequence. Therefore, the optimum of the language modeling objective is also the optimum of the supervised objective. The question is whether it can actually be optimized that far, and model size is essential for this.

If the model is not large enough, zero-shot performance does not even reach simple baselines. On the paper's question answering task (Natural Questions), GPT-2 answered 4.1% correctly, but the smallest model (117M) could not exceed the 1.0% of a method that simply returns the most common answer for each question type (who, what, where, etc.).

Experimental results

Language modeling datasets (zero-shot; no training or fine-tuning on any of the data. PPL is perplexity (lower is better), ACC is accuracy in %, BPB and BPC are bits per byte and per character (lower is better))

DataMetricPrevious best117M1542M (GPT-2)
LAMBADAPPL99.835.138.63
LAMBADAACC59.2345.9963.24
CBT (common nouns)ACC85.787.6593.30
CBT (named entities)ACC82.383.489.05
WikiText-2PPL39.1429.4118.34
PTBPPL46.5465.8535.76
enwik8BPB0.991.160.93
text8BPC1.081.170.98
WikiText-103PPL18.337.5017.48
1B Word BenchmarkPPL21.875.2042.16

Large improvements were seen on PTB and WikiText-2, which have little training data, and on LAMBADA and CBT, which require long context. On the other hand, the 1B Word Benchmark, which is shuffled at the sentence level and has no long-range structure, fell far short of previous results.

Other tasks (zero-shot)

TaskGPT-2 resultComparison
LAMBADA (predicting the last word of a passage)Accuracy 52.66% (63.24% when excluding words that cannot end a sentence)Previous language models: 19%
Winograd Schema Challenge (commonsense reasoning)Accuracy 70.70%7 points above the previous best
CoQA (conversational reading comprehension)F1 55 on validation dataSupervised BERT-based systems approach the human 89
Translation WMT-14 (BLEU)En→Fr 5, Fr→En 11.5Best unsupervised Fr→En translation: 33.5
Natural Questions (question answering)Exact match 4.1%Returning the most common answer: 1.0%

Summarization (CNN / Daily Mail, ROUGE F1)

MethodROUGE-1ROUGE-2ROUGE-LAverage
Previous best (Bottom-Up Sum)41.2218.6838.3432.75
First 3 sentences of the article40.3817.6636.6231.55
GPT-2 (with TL;DR:)29.348.2726.5821.40
3 random sentences from the article28.788.6325.5220.98
GPT-2 (without TL;DR:)21.584.0319.4715.03

Summarization only slightly outperformed choosing 3 random sentences. The generated summaries looked like summaries, but they tended to focus on content near the end of the article or confused specific details, such as how many cars were involved in an accident.

Caveats when using it

When using GPT-2, keep the following points in mind.

  • Factual correctness is not guaranteed: as with the details confused in summarization, it can generate plausible but incorrect text.
  • Zero-shot performance is far from practical on some tasks: the paper also says that performance on tasks such as summarization is "still rudimentary," and that on many practical tasks it is likely no better than random. For practical use, consider fine-tuning.
  • Context is limited to 1024 tokens: position embeddings go up to position 1024. Long documents need to be split.
  • The output changes greatly with the decoding method: greedy decoding tends to repeat the same phrases, and the paper uses top-k sampling (k=2k = 2) for summarization to reduce repetition. Nucleus sampling and others are also used.
  • Check whether evaluation data is contained in the training data: the paper checked for overlapping 8-word sequences and reports that 1–6% (3.2% on average) of common language modeling evaluation data also appears in WebText.

The GPT-2 tokenizer in Hugging Face has no padding token. When batching multiple sentences, specify something like tokenizer.pad_token = tokenizer.eos_token and pass attention_mask. Also, when generating continuations with a decoder-only model, padding must be placed on the left (padding_side="left"). If it is placed on the right, the position right before generation becomes padding.

Comparison with other models

Comparing the GPT family and BERT from the same viewpoints gives the following.

ModelArchitectureLargest parameter countTraining dataContext lengthMain use
GPTDecoder only (12 layers, Post-LN)117M (12 layers, 768 dimensions)BooksCorpus512Fine-tuned for each task
BERTEncoder only (up to 24 layers)340MBooksCorpus + Wikipedia512Fine-tuned for each task
GPT-2Decoder only (up to 48 layers, Pre-LN)1542MWebText (40 GB)1024Instructed in text without fine-tuning

The GPT-2 paper also lists fine-tuning, as done with GPT, as future work, and says it is not yet clear whether additional data and capacity can overcome the weakness of unidirectional representations demonstrated by BERT.

Rough guidelines for choosing are as follows.

  • To try text generation easily or to learn how language models work: the publicly released GPT-2 comes in four sizes, and the smaller ones can run on a local GPU or even a CPU.
  • For sentence classification or extraction: fine-tuning an encoder-only model such as BERT is a better fit.
  • To have the model solve various tasks from instructions alone: consider successor models trained at larger scale, such as GPT-3 and LLaMA.

PyTorch example

Show code
python
import math
import torch
from transformers import AutoTokenizer, GPT2LMHeadModel

"""
Example of loading and using pre-trained GPT-2 with Hugging Face transformers
  "gpt2" is the smallest model in the paper (12 layers, 768 dimensions). "gpt2-medium", "gpt2-large", and "gpt2-xl" are the other three sizes
1. Generate a continuation of a text
2. Compute the perplexity of a sentence (how easy it is for the language model to predict)
3. Prompt a summary with "TL;DR:" as in the paper (zero-shot)
"""

name = "gpt2"
tokenizer = AutoTokenizer.from_pretrained(name)      # Byte-level BPE (vocabulary of 50,257)
model = GPT2LMHeadModel.from_pretrained(name)
model.eval()                                         # Disable dropout

# --- 1. Generate a continuation ---
inputs = tokenizer("Deep learning is", return_tensors="pt")
with torch.no_grad():
  out = model.generate(
    **inputs,
    max_new_tokens=40,
    do_sample=True, top_k=40,                        # Sample from the top 40 tokens
    pad_token_id=tokenizer.eos_token_id)             # GPT-2 has no padding token, so use EOS
print(tokenizer.decode(out[0], skip_special_tokens=True))

# --- 2. Compute perplexity ---
text = "The quick brown fox jumps over the lazy dog."
enc = tokenizer(text, return_tensors="pt")
with torch.no_grad():
  # Passing the same sequence as labels makes the model shift it by one and compute the next-token cross-entropy
  loss = model(**enc, labels=enc["input_ids"]).loss
print(f"Perplexity: {math.exp(loss.item()):.1f}")

# --- 3. Prompt a summary with "TL;DR:" (Section 3.6 of the paper generates 100 tokens with top_k=2 and uses the first 3 sentences) ---
article = "..."                                      # The English article to summarize
prompt = article + "\nTL;DR:"
enc = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=1024 - 100)  # Context is limited to 1024 tokens
with torch.no_grad():
  out = model.generate(**enc, max_new_tokens=100, do_sample=True, top_k=2,
                       pad_token_id=tokenizer.eos_token_id)
print(tokenizer.decode(out[0, enc["input_ids"].size(1):], skip_special_tokens=True))

FAQ

Q. What is the difference between GPT and GPT-2?
A.

The architecture is almost the same; the main differences are size and training data. GPT-2 has up to 48 layers and 1.5 billion parameters, more than 10 times GPT, and its training data is WebText (40 GB) from web pages rather than books. Architecturally, layer normalization is moved to the input side of each sublayer (Pre-LN), one normalization is added at the end, and the context is extended to 1024 tokens. In terms of usage, the paper focuses on zero-shot instruction by text rather than fine-tuning for each task.

Q. What is zero-shot?
A.

It means having a trained model solve a task without using a single training example for that task. GPT-2 conveys the task only through how the input text is written, for example by appending "TL;DR:" to prompt a summary or by listing "English sentence = French sentence" examples to prompt translation. The model's weights are not changed.

Q. Why was the position of layer normalization changed?
A.

The paper explains that it follows the same idea as the improved ResNet that applies activation before the residual addition. With Pre-LN, the input flows directly to the next layer along the residual path without passing through normalization, which is said to make training more stable even for deeper networks. Since the output of the last layer is not normalized, one layer normalization is added at the end.

References

  1. Radford, A., Wu, J., Child, R., Luan, D., Amodei, D., & Sutskever, I. (2019). Language Models are Unsupervised Multitask Learners. OpenAI.
  2. Radford, A., Narasimhan, K., Salimans, T., & Sutskever, I. (2018). Improving Language Understanding by Generative Pre-Training. OpenAI.
  3. Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., Kaiser, Ł., & Polosukhin, I. (2017). Attention Is All You Need. NIPS 2017.
  4. Hugging Face. Transformers documentation: OpenAI GPT2.