AI Logic

Architectures

GPT-3

Updated:

Architecture and usage of GPT-3. The left side shows the overall flow (token sequence, token and position embeddings, 12 to 96 decoder layers alternating between dense attention and locally banded sparse attention, a final layer normalization, next-token prediction) and the range each of the two attention types can see. The right side shows example inputs for the three in-context learning settings (zero-shot, one-shot, few-shot) and how they are fed into GPT-3, whose weights are not updated, to generate the answer as a continuation

Background and overview

GPT-3 is a language model that scales a decoder-only Transformer, nearly identical to GPT-2, up to 175 billion parameters, and shows that it can solve new tasks without updating its weights, simply by writing a few examples of the task into the input text. It was presented by Brown et al. at OpenAI in 2020 in the paper "Language Models are Few-Shot Learners." At 175 billion parameters, it is 10 times larger than any previous non-sparse language model.

Until then, models such as GPT and BERT were used by pre-training and then fine-tuning on thousands to hundreds of thousands of labeled examples for each task. The GPT-3 paper points out three problems with this approach.

  • Every new task requires collecting a large labeled dataset.
  • Fine-tuning on narrow data makes it easy to pick up accidental quirks of that data, which makes true generalization ability hard to measure.
  • Humans can perform a new task after seeing only a short instruction or a few examples.

The paper therefore calls the approach of placing a task description and examples in the input text and having the model solve the task simply by predicting the continuation in-context learning, and studies it in three settings that differ in the number of examples.

SettingWhat goes in the inputWeight updates
Zero-shotTask description onlyNone
One-shotTask description and 1 exampleNone
Few-shotTask description and KK examples (typically 10 to 100)None

As a result, GPT-3 in the few-shot setting matched or exceeded the best fine-tuned results of the time on TriviaQA, a knowledge-based question answering task (71.2% accuracy), and on LAMBADA, which asks for the last word of a passage (86.4%). It also showed that the larger the model, the more it gains from seeing examples. On the other hand, on tasks that compare two sentences (WiC, ANLI), even few-shot performance was close to random guessing.

Architecture: changes from GPT-2

The architecture of GPT-3 is the same as GPT-2. It keeps the modified initialization, the normalization placed at the input of each sub-layer (Pre-LN), and byte-level BPE. The left side of the figure at the top of the article shows the overall flow and the range attention can see. There are only two changes from GPT-2.

  1. Dense attention and locally banded sparse attention alternate from layer to layer. In the banded layers, each token attends only to tokens near itself. This follows the same idea as the Sparse Transformer and keeps the cost down for long contexts.
  2. The context length is 2048 tokens (1024 in GPT-2). This length determines how many examples can be placed in a few-shot prompt.

The paper does not give details such as the band width or which layers are sparse. The study focuses less on architectural changes and more on how performance changes with scale.

Eight models of different sizes were all trained on 300 billion tokens (Table 2.1 of the paper). The inner size of the feed-forward layer is 4 times dmodeld_{\text{model}} in every model.

ModelParametersLayersdmodeld_{\text{model}}HeadsHead dimensionBatch (tokens)Learning rate
GPT-3 Small125M1276812640.5M6.0Ɨ10āˆ’46.0 \times 10^{-4}
GPT-3 Medium350M24102416640.5M3.0Ɨ10āˆ’43.0 \times 10^{-4}
GPT-3 Large760M24153616960.5M2.5Ɨ10āˆ’42.5 \times 10^{-4}
GPT-3 XL1.3B242048241281M2.0Ɨ10āˆ’42.0 \times 10^{-4}
GPT-3 2.7B2.7B32256032801M1.6Ɨ10āˆ’41.6 \times 10^{-4}
GPT-3 6.7B6.7B324096321282M1.2Ɨ10āˆ’41.2 \times 10^{-4}
GPT-3 13B13B405140401282M1.0Ɨ10āˆ’41.0 \times 10^{-4}
GPT-3 175B (GPT-3)175B9612288961283.2M0.6Ɨ10āˆ’40.6 \times 10^{-4}

Larger models use larger batches and smaller learning rates. This follows earlier findings that larger models can use larger batches but need smaller learning rates.

Training: data and settings

Training is next-token prediction only, as in GPT-2. Treating a text xx as a sequence of tokens (s1,…,sn)(s_1, \dots, s_n), the model maximizes the following probability (the loss is cross-entropy).

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 is mainly web text (Common Crawl), mixed with higher-quality datasets (Table 2.2 of the paper).

DatasetTokensWeight in training mixEpochs elapsed when training for 300B tokens
Common Crawl (filtered)410B60%0.44
WebText219B22%2.9
Books112B8%1.9
Books255B8%0.43
Wikipedia3B3%3.4

The weights are not proportional to dataset size; datasets considered higher quality are sampled more often. This accepts a little overfitting in exchange for learning from more high-quality text. Because raw Common Crawl is low in quality, it was cleaned in three steps.

  1. Train a classifier (logistic regression) to distinguish high-quality text such as GPT-2's WebText from unfiltered Common Crawl, and preferentially keep documents judged to be high quality.
  2. Remove similar documents within and across datasets (deduplication with MinHashLSH; this reduced the data by 10% on average).
  3. Add existing high-quality datasets (WebText2, books, and English Wikipedia).

The optimization settings (Appendix B of the paper) are as follows.

  • Optimizer: Adam (β1=0.9\beta_1 = 0.9, β2=0.95\beta_2 = 0.95, ϵ=10āˆ’8\epsilon = 10^{-8}). Weight Decay of 0.1
  • Learning rate: linear warmup over the first 375 million tokens, then decayed to 10% with a cosine schedule by 260 billion tokens, and held at 10% afterward
  • Batch: starts at 32k tokens and increases linearly over the first 4 to 12 billion tokens (depending on model size)
  • Gradients: the global norm is clipped at 1.0 (to prevent exploding gradients)
  • Input: always trained on sequences of 2048 tokens. Short documents are packed into a single sequence, separated by an end-of-document token

Training ran on a cluster of Microsoft V100 GPUs, with the model split both within individual matrix multiplications and across layers (the ideas of tensor parallelism and pipeline parallelism). According to the estimate in Appendix D of the paper, training GPT-3 175B took about 3.14Ɨ10233.14 \times 10^{23} floating-point operations.

Usage: in-context learning

GPT-3 is used by describing the task in the input text and having it generate the continuation. The right side of the figure at the top of the article shows a task of translating English into French written in the three settings (the same as Figure 2.1 of the paper).

  • Zero-shot: after "Translate English to French:", place the word to translate, "cheese =>".
  • One-shot: after the task description, place one example, "sea otter => loutre de mer", and finally "cheese =>".
  • Few-shot: place KK examples. KK is however many fit in the 2048-token context, typically 10 to 100.

In every setting, the model's weights are not changed and no gradients are computed. The model solves the task by "continuing the text in the same form as the examples."

The evaluation method (Section 2.4 of the paper) depends on the type of task.

Task typeHow the answer is obtained
Multiple choicePlace the question after the examples and compare the probability of continuing with each choice. Usually the per-token probability is compared to remove the effect of length
Binary classificationUse meaningful words such as "True" and "False" instead of 0 and 1, and compare them as in multiple choice
Free-formGenerate with beam search (width 4, length penalty α=0.6\alpha = 0.6) and score with F1, BLEU, or exact match

For some multiple-choice tasks (ARC, OpenBookQA, RACE), results improved by comparing the following ratio, which removes the effect of how likely each choice is on its own. "Answer: " is a fixed string that only signals that an answer follows.

P(choice∣question)P(choice∣"Answer: ")\frac{P(\text{choice} \mid \text{question})}{P(\text{choice} \mid \text{"Answer: "})}

For each evaluated question, KK examples are drawn at random from that task's training set.

Why showing examples is enough

The paper explains language model pre-training as learning at two levels (meta-learning).

  • Outer loop: during pre-training, the model acquires a wide range of skills and pattern-recognition ability from a large amount of text.
  • Inner loop: at use time, within a single input text, the model reads from the examples "what task is being done right now" and continues the text accordingly. This is in-context learning.

Web text contains small tasks of the same form that repeat within a single document (for example, text listing many word translation pairs, or text with questions and answers in sequence). Predicting the next token requires spotting the rule of such repetition partway through the document, so pre-training itself serves as practice for the inner loop. As an analogy, it resembles a person who has worked through many workbooks and, faced with a new question format, can figure out what to do after seeing worked answers to the first few questions.

This ability grew stronger with model size. In Figure 1.3 of the paper, averaged over 42 benchmarks, zero-shot performance rises steadily with model size, and few-shot performance rises faster. Because the gap between zero-shot and few-shot widens for larger models, the paper states that "larger models are more proficient meta-learners." In arithmetic too, the 13-billion-parameter model solved only about half of 2-digit additions and subtractions, while the 175-billion model solved 2-digit addition 100% of the time in the few-shot setting.

Even the paper does not know whether in-context learning truly "learns" a task anew at use time or "merely recognizes" a task seen during pre-training. The paper considers that it depends on the task: tasks such as using made-up words or unscrambling letters are likely learned anew, while translation must have been acquired during pre-training.

Experimental results

The paper evaluated the 8 model sizes in the 3 settings on more than 24 datasets. The results below are for GPT-3 175B.

Passage-completion tasks and knowledge-based question answering (accuracy %. LAMBADA PPL is perplexity, lower is better. Tables 3.2 and 3.3 of the paper)

DatasetZero-shotOne-shotFew-shotPrevious best
LAMBADA (accuracy)76.272.586.468.0
LAMBADA (PPL)3.003.351.928.63
HellaSwag78.978.179.385.6
TriviaQA64.368.071.268.0 (fine-tuned model that retrieves external documents)
NaturalQuestions14.623.029.944.5 (same as above)

The few-shot 71.2% on TriviaQA beat not only the model fine-tuned to answer without external documents (T5-11B at 50.1%) but also the model that retrieves documents.

Reading comprehension, commonsense reasoning, and SuperGLUE (Tables 3.6 to 3.8 of the paper. CoQA and DROP are F1, the rest are accuracy %)

DatasetZero-shotFew-shotBest fine-tuned
CoQA (conversational reading comprehension)81.585.090.7
DROP (reading comprehension with counting)23.636.589.1
RACE-h (middle/high school reading comprehension)45.546.890.0
PIQA (physical commonsense)81.082.879.4
ARC (Challenge)51.451.578.5
SuperGLUE (average)-71.889.0 (BERT-Large: 69.0)
WiC (whether a word has the same meaning in 2 sentences)-49.476.1

Results varied widely by task. GPT-3 exceeded the best result on PIQA, but fell far short on tasks that require rereading and comparing a long passage, such as DROP and RACE, and on tasks that compare two sentences, such as WiC. The 49.4% on WiC is the same as random guessing (50%).

Translation (BLEU. Table 3.4 of the paper)

SettingEn→FrFr→EnEn→DeDe→EnEn→RoRo→En
Best supervised45.635.041.240.238.539.9
GPT-3 zero-shot25.221.224.627.214.119.9
GPT-3 few-shot32.639.229.740.621.039.5

Because 93% of the training data is English (by word count), translation into English gave better results.

Arithmetic (few-shot, accuracy %. Table 3.9 of the paper)

2-digit addition2-digit subtraction3-digit addition3-digit subtraction4-digit addition5-digit addition2-digit multiplication
100.098.980.494.225.59.329.2

The paper reports that of 2,000 3-digit addition problems, only 17 (0.8%) appeared verbatim in the training data, and concludes that the model is not merely memorizing answers.

Detecting generated news articles: when people read news articles of about 200 words and were asked whether a machine wrote them, they identified 86% of the articles from a deliberately degraded model, but only 52% of those from GPT-3 175B, barely different from random guessing (50%) (Table 3.11 of the paper).

Caveats in practice

When using a large language model such as GPT-3, keep the following points in mind.

  • Weak on tasks that compare two sentences: on WiC and ANLI, even few-shot performance was close to random guessing. The paper suggests that its left-to-right, one-directional architecture may make tasks that require rereading and comparing long passages difficult.
  • Coherence breaks down in long text: as a document grows longer, the model may repeat itself or contradict earlier content.
  • The number of examples is limited by the context length: examples can only fill up to 2048 tokens. For tasks with long examples, fewer of them fit.
  • Inference is expensive: a 175-billion-parameter model needs large computational resources even for inference. The paper suggests knowledge distillation into smaller task-specific models as one direction.
  • Bias and misuse: Section 6 of the paper reports that biases related to gender, race, and religion appear in generated text, and that text hard to distinguish from human writing could be misused.

Care is needed to make sure evaluation data has not leaked into the training data. The GPT-3 paper tried to remove overlaps with evaluation data from the training data, but a bug in the filtering program left some of them in, and the cost of training made it impossible to retrain. Section 4 of the paper examines the impact and either omits or flags results on datasets where the impact may be large. The same problem can occur whenever a model trained on web text is measured on evaluation data that is available on the web.

Comparison with other models

Comparing the GPT family and large language models that came after GPT-3 from the same angles gives the following (parameter and token counts from each paper and Table 1 of the Chinchilla paper; - means not stated in the paper).

ModelLargest parameter countTraining tokensContext lengthMain usage
GPT117M- (BooksCorpus)512Fine-tune for each task
GPT-21.5B- (WebText, 40 GB)1024Zero-shot, instructed in text
GPT-3175B300B2048Few-shot, shown examples
Gopher280B300B2048Zero-shot and few-shot
Chinchilla70B1.4T- (not stated in the paper)Few-shot

After GPT-3, many large language models followed it and were trained on about 300 billion tokens. In contrast, the Chinchilla study showed that, for the same compute, it is better to use a smaller model trained on more tokens, and that models like GPT-3 were undertrained.

Rough guidelines for choosing are as follows.

  • To learn the idea of in-context learning: the GPT-3 paper is the starting point. Conveying a task only through the input text, without changing weights, became the basic way of using later large language models.
  • To try it locally: GPT-3's weights are not public. You can experiment with building few-shot prompts using GPT-2, which has a similar architecture, or the openly released LLaMA. In the LLaMA paper, the 13-billion-parameter LLaMA outperforms GPT-3 on most benchmarks.
  • To train a better model with the same compute: following the idea of Chinchilla, scale model size and the number of training tokens in equal proportion.

PyTorch example

Show code
python
import torch
import torch.nn.functional as F
from transformers import AutoTokenizer, AutoModelForCausalLM

"""
GPT-3's weights are not public, so this example uses GPT-2, which has a similar architecture, to reproduce the evaluation method in Section 2.4 of the paper
1. Build a few-shot input (task description + K examples + question)
2. Solve a multiple-choice task by comparing the "per-token log probability" of continuing with each choice
3. Build a mask in the shape of GPT-3's "locally banded sparse attention" (the band width is not in the paper, so this is an example)
Weights are not updated (no gradients are computed). model.eval() disables dropout
"""

name = "gpt2"
tokenizer = AutoTokenizer.from_pretrained(name)
model = AutoModelForCausalLM.from_pretrained(name)
model.eval()

# --- 1. Few-shot input (same form as Figure 2.1 of the paper) ---
def few_shot_prompt(description, examples, query):
  lines = [description] + [f"{x} => {y}" for x, y in examples] + [f"{query} =>"]
  return "\n".join(lines)

prompt = few_shot_prompt(
  "Translate English to French:",
  [("sea otter", "loutre de mer"), ("peppermint", "menthe poivrƩe")],   # K = 2 (K = 0 is zero-shot)
  "cheese")

# --- 2. Compare choices by per-token log probability ---
@torch.no_grad()
def score(context, completion):
  ctx = tokenizer(context, return_tensors="pt")["input_ids"]
  comp = tokenizer(" " + completion, return_tensors="pt")["input_ids"]
  ids = torch.cat([ctx, comp], dim=1)
  logp = F.log_softmax(model(ids).logits[0, :-1], dim=-1)   # the output at position t predicts token t+1
  target = ids[0, 1:]
  lp = logp[torch.arange(target.size(0)), target][-comp.size(1):]   # only the choice part
  return lp.mean().item()                                   # average to remove the effect of length

choices = ["fromage", "chien", "voiture"]
scores = {c: score(prompt, c) for c in choices}
print(max(scores, key=scores.get), scores)

# --- 3. Mask for locally banded sparse attention ---
def banded_causal_mask(n, band):
  i = torch.arange(n).unsqueeze(1)          # attending side
  j = torch.arange(n).unsqueeze(0)          # attended side
  return (j <= i) & (i - j < band)          # attend only where True (never to the right of itself)

dense = banded_causal_mask(6, band=6)       # dense: itself and everything to its left
local = banded_causal_mask(6, band=3)       # banded: only the 3 nearest tokens (width is an example)
# GPT-3 alternates dense and local from layer to layer. Can be passed as attn_mask to scaled_dot_product_attention
q = k = v = torch.randn(1, 1, 6, 8)
out = F.scaled_dot_product_attention(q, k, v, attn_mask=local)

FAQ

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

The architecture is nearly the same; the main differences are scale and usage. GPT-3 has up to 96 layers and 175 billion parameters, more than 100 times GPT-2 (1.5 billion), and extends the context to 2048 tokens. The only architectural change is alternating dense attention and locally banded sparse attention from layer to layer. In terms of usage, GPT-2 mainly studied zero-shot, while GPT-3 focused on few-shot, placing examples in the input, and showed that performance improves as more examples are shown.

Q. How does in-context learning differ from fine-tuning?
A.

Fine-tuning computes gradients on task data and rewrites the model's weights. In-context learning leaves the weights unchanged and simply writes a task description and examples into the input text. In-context learning needs almost no task-specific data and lets one model be reused for many tasks, but at the time of the GPT-3 paper it still fell short of the best fine-tuned models on many tasks.

Q. Are more few-shot examples always better?
A.

In the paper, increasing the number of examples KK improved performance on many tasks. Because this is not always the case, however, the paper tried several values of KK on validation data and used the best one. Examples can only fill up to the 2048-token context, so for tasks with long examples the number that fits is limited.

References

  1. Brown, T. B., Mann, B., Ryder, N., Subbiah, M., et al. (2020). Language Models are Few-Shot Learners. NeurIPS 2020.
  2. Radford, A., Wu, J., Child, R., Luan, D., Amodei, D., & Sutskever, I. (2019). Language Models are Unsupervised Multitask Learners. OpenAI.
  3. Child, R., Gray, S., Radford, A., & Sutskever, I. (2019). Generating Long Sequences with Sparse Transformers. arXiv:1904.10509.
  4. Hoffmann, J., Borgeaud, S., Mensch, A., et al. (2022). Training Compute-Optimal Large Language Models. arXiv:2203.15556.