AI Logic

Architectures

Gopher

Updated๏ผš

Structure of Gopher. The left side shows the overall flow (a SentencePiece token sequence, token embeddings without positional embeddings, repeated decoder layers, a final RMSNorm, and next-token prediction) and the sampling proportions from the MassiveText training data (MassiveWeb 48%, Books 27%, C4 10%, News 10%, GitHub 3%, Wikipedia 2%). The right side shows the inside of a decoder layer (causal self-attention with relative positional encoding and a feed-forward network, each with RMSNorm on the input side)

Background and Overview

Gopher is a language model that scales a decoder-only Transformer of the same form as GPT-2 up to 280 billion parameters and trains it on English text collected with an emphasis on quality (MassiveText). Rae et al. of DeepMind presented it in 2021 in the paper "Scaling Language Models: Methods, Analysis & Insights from Training Gopher."

The core of the paper is not a new architecture but a study, across many tasks, of what improves and what does not when a model is scaled up. Six models ranging from 44 million to 280 billion parameters were trained on the same data for the same 300 billion tokens and compared on 152 tasks.

The results can be summarized as follows.

  • On 100 of the 124 tasks where comparison was possible (81%), it outperformed the best results of contemporary large language models such as GPT-3.
  • On knowledge-intensive tasks such as reading comprehension, fact-checking, and the humanities and medicine, scaling up brought large gains. For example, its 5-shot accuracy on MMLU (exam questions across 57 subjects) was 60.0%, far above GPT-3's 43.9%.
  • On mathematics, logical reasoning, and common sense tasks, however, scaling up brought small gains, and on some tasks it performed worse than smaller models.

Beyond performance analysis, the paper also reports in detail on how the training data was built, how toxic generation and bias relate to model size, and how to use the model for dialogue. Later, DeepMind's own Chinchilla study showed that, for the same compute as Gopher, it is better to train a model one quarter the size on four times as much data.

Architecture: Changes from GPT-2

Gopher's architecture is GPT-2's autoregressive Transformer with the following two changes (Section 3.1 of the paper). In the figure at the top of the article, the left side shows the overall flow and the right side shows the inside of one decoder layer.

  1. Replace layer normalization with RMSNorm. This normalization does not subtract the mean; it only rescales by dividing by the root mean square. As in GPT-2, normalization is applied on the input side of each sublayer (Pre-LN).
  2. Drop absolute positional embeddings in favor of Transformer-XL's relative positional encoding. The distance between tokens is used inside attention. Because the model can be evaluated on sequences longer than those seen in training, it handles long texts such as books and articles better.

RMSNorm normalizes dd values a1,โ€ฆ,ada_1, \dots, a_d as follows (gig_i is a learned gain).

aห‰i=aiRMS(a)โ€‰gi,RMS(a)=1dโˆ‘i=1dai2\bar{a}_i = \frac{a_i}{\mathrm{RMS}(\boldsymbol{a})}\, g_i, \qquad \mathrm{RMS}(\boldsymbol{a}) = \sqrt{\frac{1}{d}\sum_{i=1}^{d} a_i^2}

Tokenization uses SentencePiece with a 32,000-token vocabulary. Characters outside the vocabulary are represented by falling back to bytes (byte-level fallback), so any string can be handled.

The paper trained six models of different sizes (Table 1 of the paper). In every model, the feed-forward hidden size is 4 times dmodeld_{\text{model}}.

ModelLayersHeadsKey/value sizedmodeld_{\text{model}}Max learning rateBatch (tokens)
44M816325126ร—10โˆ’46 \times 10^{-4}0.25M
117M1212647686ร—10โˆ’46 \times 10^{-4}0.25M
417M12121281,5362ร—10โˆ’42 \times 10^{-4}0.25M
1.4B24161282,0482ร—10โˆ’42 \times 10^{-4}0.25M
7.1B32321284,0961.2ร—10โˆ’41.2 \times 10^{-4}2M
Gopher 280B8012812816,3844ร—10โˆ’54 \times 10^{-5}3M โ†’ 6M

Training: MassiveText and Training Setup

The training data (MassiveText) is a collection of English text from web pages, books, news, code, and more, totaling about 2.35 billion documents and 10.5 TB (Table 2 of the paper). Gopher uses only 300 billion tokens of it (12.8%), so a sampling proportion is set for each subset.

SubsetSizeDocumentsTokensSampling proportion in training
MassiveWeb (web pages)1.9 TB604M506B48%
Books2.1 TB4M560B27%
C40.75 TB361M182B10%
News2.7 TB1.1B676B10%
GitHub3.1 TB142M422B3%
Wikipedia0.001 TB6M4B2%

The share of books (27%) is higher than in GPT-3 (16%), which the paper considers one reason why prediction of book and academic text improved particularly well.

MassiveWeb, the most heavily used subset, was built in the following six stages (Appendix A.1 of the paper). The other subsets go through only stages 1, 5, and 6.

  1. Content filtering: Remove non-English documents. For MassiveWeb, also remove pages flagged as inappropriate by Google SafeSearch.
  2. Text extraction: Find coherent blocks of body text in the HTML tree and turn them into text, preserving indentation, line breaks, and bullet points.
  3. Quality filtering: Remove low-quality documents with simple rules. These include documents with fewer than 50 or more than 100,000 words, a mean word length outside 3โ€“10 characters, or "#" or "โ€ฆ" making up more than 10% of words. Documents that do not contain at least two common English words such as "the," "be," and "to" are also removed.
  4. Repetition removal: Remove documents with many repeated lines, paragraphs, or n-grams.
  5. Deduplication: Remove near-duplicate documents.
  6. Test-set filtering: Remove documents that closely resemble evaluation data.

In the paper's experiments, each additional stage improved the task performance of the trained model, showing the importance of data quality.

The training setup (Section 3.2 of the paper) is as follows.

  • Optimizer: Adam
  • Learning rate: warmup from 10โˆ’710^{-7} to the maximum over the first 1,500 steps, then cosine decay to one tenth
  • Gradients: clip the global norm at 1.0; for 7.1B and Gopher, use 0.25 for training stability
  • Numerical format: bfloat16. Models below 7.1B use mixed-precision training with float32 weights; 7.1B and Gopher keep the weights in bfloat16 as well

Training was done on TPUv3. Gopher's weights and Adam state total 2.5 TiB, which does not fit in a single core's memory (16 GiB), so the authors combined optimizer state partitioning (ZeRO), model parallelism (Megatron-LM), and recomputing values during backpropagation (gradient checkpointing). Within a TPU pod they used model parallelism and data parallelism, and across pods they used pipeline parallelism. Training Gopher took 920 hours on 4,096 TPUv3 chips.

Why Gains Differ by Task

Because Gopher's six models were trained on the same data for the same number of tokens, the effect of changing only model size can be isolated and compared. The paper compared Gopher (280B) with the best results of models of 7.1B or smaller on 152 tasks.

Gain from scaling upNumber of tasks
No gain or worse16 (10.5%)
Small gain (25% or less)57 (37.5%)
Large gain (more than 25%)79 (51.2%)

The percentages are as written in the paper; 79 รท 152 works out to 52.0%.

The largest gains came on medicine, science, technology, social science, and humanities tasks. For example, on BIG-bench's figure-of-speech detection task, accuracy rose from 16.8% for the 7.1B model to 52.7% for Gopher. By contrast, mathematics, logical reasoning, and common sense tasks improved little, and on abstract algebra and high school mathematics, Gopher did worse than smaller models.

The paper explains this difference in terms of the training objective of language models. A language model is trained to predict (compress) text well. Connections between facts about the world improve prediction the more of them are memorized, so gains grow with size. Mathematical procedures, on the other hand, are hard to compress as text and may not be acquired simply by scaling up.

As an analogy, adding more books to a library increases the facts you can look up, but more books do not make you calculate faster.

An analysis of fact-checking (FEVER) showed the same tendency. Scaling up improved the ability to distinguish "supported claims" from "refuted claims," but not the ability to distinguish "refuted claims" from "claims with not enough information." The paper concludes that larger models do not understand misinformation more deeply; rather, they know more facts.

Experimental Results

Knowledge and reading comprehension (all accuracy in %; Tables 4, 5, and A15 of the paper)

BenchmarkSettingGopher 280BGPT-3 175B7.1BComparison
MMLU (average over 57 subjects)5-shot60.043.9-Human expert average 89.8
RACE-h (high school reading)Few-shot71.646.830.6Megatron-Turing NLG 530B: 47.9
RACE-m (middle school reading)Few-shot75.158.131.8-
Natural Questions64-shot28.229.916.5-
Natural Questions0-shot10.114.66.1-

The 60.0% on MMLU was a level that expert forecasters in September 2021 had expected to be reached around June 2022 to June 2023. On RACE reading comprehension, models of 7.1B or smaller performed about the same as random guessing (25%), showing that the combination of size and data matters. On the knowledge-heavy Natural Questions, however, Gopher fell slightly short of GPT-3, which the paper attributes to a smaller share of Wikipedia in its training data than in GPT-3's.

Commonsense reasoning (0-shot, accuracy in %; Table 8 of the Chinchilla paper)

BenchmarkGopher 280BGPT-3 175BMegatron-Turing NLG 530B
HellaSwag79.278.980.2
PIQA81.881.082.0
WinoGrande70.170.273.0
SIQA (social common sense)50.6--

On commonsense reasoning, the differences among models from 175B to 530B parameters are small, and the Gopher paper suggests that scaling beyond today's largest models may not bring much improvement on these tasks.

Toxicity and bias (Chapter 5 of the paper)

  • With toxic prompts: The more toxic the prompt (RealToxicityPrompts), the more likely larger models were to generate toxic continuations (leveling off around 7.1B).
  • Without prompts: Text generated unconditionally had low toxicity, which did not increase with size.
  • Bias: Associations between gender and occupation, and sentiment bias in text about different groups, did not consistently decrease with size. The perplexity on posts written in African American English was high at every size, and the gap did not shrink with scale.

Practical Considerations

Keep the following points in mind when building or using large language models like Gopher.

  • Scaling up does little for reasoning: The paper notes that on mathematics and logic tasks, large improvements are hard to expect from size alone.
  • Bias does not disappear with size: Models reflect the biases in their training data, so output bias needs to be examined separately.
  • Dialogue prompting does not yield a reliable dialogue model: The paper had Gopher hold conversations using a prompt describing its role and behavior (Dialogue-Prompted Gopher). It could hold plausible conversations but often stated incorrect facts with confidence. In human evaluation (1,400 ratings), there was no difference in preference compared with a model fine-tuned on just 5 billion tokens of dialogue data.
  • Overlap between training and evaluation data: The paper removed documents resembling evaluation data but cautions that some overlap may remain.

Appendix C of the paper also reports what did not work. When Gopher was trained with its weights in bfloat16, weight updates were too small to register because of the small learning rate, and many layers stopped changing partway through training. In addition, the memory-efficient Adafactor worked fine for small models but made training unstable for the 7.1B model. Its successor Chinchilla keeps a float32 copy of the weights in the optimizer state and uses AdamW.

Comparison with Other Models

Comparing Gopher with large language models from the same period on the same criteria gives the following (parameter and training token counts from Table 1 of the Chinchilla paper; MMLU is 5-shot).

ModelParametersTraining tokensArchitectural featuresMMLU
GPT-3175B300BAlternates dense attention with locally banded sparse attention43.9
Gopher280B300BRMSNorm and relative positional encoding60.0
Chinchilla70B1.4TSame as Gopher (only training settings such as AdamW change)67.6

Chinchilla used the same compute as Gopher to train a model one quarter the size on about 4.7 times as many tokens, and it outperformed Gopher on nearly every task. This means that Gopher, like many models of its time, was trained on too little data for its size.

Rough guidelines for choosing:

  • You want to know how large language model performance changes with size: The Gopher paper is a detailed resource that compares six sizes trained on the same data across 152 tasks.
  • You want a reference for building training data: MassiveWeb's filtering rules (Appendix A) rely only on simple rules, and the same approach can be applied to other data.
  • You want a better-performing model for the same compute: Follow the Chinchilla approach of increasing data rather than size.
  • You want to keep inference costs down: Open models such as LLaMA, which train smaller models for longer, are a good fit. Gopher's weights have not been released.

PyTorch example

Show code
python
import re
import torch
import torch.nn as nn

"""
A small example of two elements from the Gopher paper
1. RMSNorm: used instead of GPT-2's layer normalization (placed on the input side of each sublayer)
2. MassiveWeb's quality filtering rules ("Quality Filtering" in Appendix A.1.1 of the paper)
RMSNorm has no dropout, so model.train() and model.eval() compute the same thing
"""

class RMSNorm(nn.Module):
  def __init__(self, dim, eps=1e-6):
    super().__init__()
    self.eps = eps
    self.weight = nn.Parameter(torch.ones(dim))   # gain g

  def forward(self, x):
    rms = torch.sqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
    return x / rms * self.weight                   # the mean is not subtracted

# PyTorch 2.4 and later also include a built-in torch.nn.RMSNorm(dim, eps=...)
x = torch.randn(2, 16, 512)                        # [batch, sequence, d_model]
print(RMSNorm(512)(x).shape)

STOP_WORDS = {"the", "be", "to", "of", "and", "that", "have", "with"}

def passes_quality_filter(doc: str) -> bool:
  words = doc.split()
  n = len(words)
  if not 50 <= n <= 100_000:                       # number of words
    return False
  mean_len = sum(len(w) for w in words) / n
  if not 3 <= mean_len <= 10:                      # mean word length (characters)
    return False
  if doc.count("#") / n > 0.1 or (doc.count("...") + doc.count("โ€ฆ")) / n > 0.1:
    return False                                   # symbol-to-word ratio
  lines = [l for l in doc.splitlines() if l.strip()]
  if lines:
    bullets = sum(l.lstrip().startswith(("โ€ข", "-", "*")) for l in lines) / len(lines)
    ellipsis_end = sum(l.rstrip().endswith(("...", "โ€ฆ")) for l in lines) / len(lines)
    if bullets > 0.9 or ellipsis_end > 0.3:        # share of bullet lines and lines ending in "โ€ฆ"
      return False
  if sum(bool(re.search("[A-Za-z]", w)) for w in words) / n < 0.8:
    return False                                   # share of words containing a letter
  if len(STOP_WORDS & {w.lower() for w in words}) < 2:
    return False                                   # at least two common English words?
  return True

FAQ

Q. How does Gopher differ from GPT-3?
A.

Both are decoder-only Transformers trained on 300 billion tokens, but Gopher, at 280 billion parameters, is larger than GPT-3 (175 billion), and architecturally it uses RMSNorm and relative positional encoding. The training data also differs: Gopher used MassiveText, which has a larger share of books. On MMLU (5-shot), Gopher scored 60.0% and GPT-3 43.9%.

Q. Does scaling up a model make it able to solve any task?
A.

According to the Gopher paper, no. Knowledge tasks and reading comprehension improved greatly with scale, but mathematics, logical reasoning, and common sense tasks improved little, and on some tasks the larger model did worse than smaller ones. On 16 of the 152 tasks (10.5%), scaling up brought no improvement.

Q. How are Gopher and Chinchilla related?
A.

Both are DeepMind models with the same architecture, the same MassiveText data, and nearly the same training compute. They differ in size and amount of data: Chinchilla trained 70 billion parameters on 1.4 trillion tokens, while Gopher trained 280 billion parameters on 300 billion tokens. The smaller, longer-trained Chinchilla outperformed Gopher on nearly every task.

References

  1. Rae, J. W., Borgeaud, S., Cai, T., Millican, K., et al. (2021). Scaling Language Models: Methods, Analysis & Insights from Training Gopher. arXiv:2112.11446.
  2. Hoffmann, J., Borgeaud, S., Mensch, A., et al. (2022). Training Compute-Optimal Large Language Models. arXiv:2203.15556.
  3. Radford, A., Wu, J., Child, R., Luan, D., Amodei, D., & Sutskever, I. (2019). Language Models are Unsupervised Multitask Learners. OpenAI.
  4. Zhang, B., & Sennrich, R. (2019). Root Mean Square Layer Normalization. NeurIPS 2019.
  5. Dai, Z., Yang, Z., Yang, Y., Carbonell, J., Le, Q. V., & Salakhutdinov, R. (2019). Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context. ACL 2019.