AI Logic

Architectures

PaLM

Updated:

Structure of PaLM. The left shows the overall flow (a SentencePiece token sequence, token embeddings without position embeddings, repeated decoder layers, and next-token prediction using the same matrix as the input embedding) and the mix of training data (social media conversations 50%, web pages 27%, books 13%, GitHub 5%, Wikipedia 4%, news 1%). The right shows the inside of a decoder layer: a parallel layer that feeds the output of a single layer normalization into both multi-query attention with RoPE and a SwiGLU feed-forward network side by side, and sums the input with the two outputs.

Background and overview

PaLM (Pathways Language Model) is a language model that scales a decoder-only Transformer to 540 billion parameters and trains it on 780 billion tokens. It was published in 2022 by Chowdhery et al. of Google in the paper "PaLM: Scaling Language Modeling with Pathways." Pathways in the name refers to Google's new training system that brings many TPUs together to train a single model.

The architecture combines changes that make training faster and more stable and make inference cheaper, such as SwiGLU, parallel layers, multi-query attention, and RoPE. It used 6,144 TPU v4 chips, and its training efficiency (the ratio of actual to theoretical peak compute throughput) was 46.2%, higher than previous large language models.

As a result, PaLM 540B achieved the following in the few-shot setting (where only a few task examples are written into the input).

  • It outperformed the previous best results of large language models on 28 of 29 widely used English tasks.
  • Combined with chain-of-thought prompting (a method that has the model write out its intermediate reasoning before the answer), it solved 58% of grade-school math word problems (GSM8K), surpassing the fine-tuned state of the art at the time (55%).
  • On BIG-bench, a collection of more than 150 difficult tasks, it outperformed the average score of people who solved the same tasks. On about 25% of the tasks, performance jumped discontinuously when scaling from 62 billion to 540 billion parameters.

It is the model that showed the few-shot ability demonstrated by GPT-3 keeps improving with further scale.

Architecture: changes from the Transformer

PaLM makes the following changes to the decoder-only configuration of the Transformer (where each position sees only itself and earlier positions) (Chapter 2 of the paper). In the figure at the top of the article, the left shows the overall flow and the right shows the inside of one decoder layer.

  1. SwiGLU: The activation function of the feed-forward network is the gated SwiGLU, which had been reported to outperform ReLU, GELU, and Swish. It requires three matrix multiplications, but it still did better in compute-matched comparisons.
  2. Parallel layers: Attention and the feed-forward network are computed side by side from the same input rather than one after the other (see the equations below). This makes training about 15% faster for large models.
  3. Multi-query attention: Each head has its own queries, while a single set of keys and values is shared across all heads. Training speed and quality are unchanged, and the cost of generating one token at a time drops greatly.
  4. RoPE: Position information is given by RoPE, which rotates queries and keys, instead of absolute or relative position embeddings, because it performs better on long sequences.
  5. Shared input and output embeddings: The token embedding matrix is also used for next-token prediction.
  6. No biases: Neither the fully connected layers nor layer normalization use biases. This made training of large models more stable.
  7. Vocabulary: A SentencePiece vocabulary of 256k. Whitespace is preserved (for code), characters not in the vocabulary are split into UTF-8 bytes (byte-level), and numbers are split into individual digits ("123.5" → "1 2 3 . 5").

The parallel layer in item 2 differs from the usual serial form as follows (xx is the input to the layer).

Serial:  y=x+MLP(LayerNorm(x+Attention(LayerNorm(x))))\text{Serial: }\ y = x + \mathrm{MLP}\bigl(\mathrm{LayerNorm}(x + \mathrm{Attention}(\mathrm{LayerNorm}(x)))\bigr) Parallel:  y=x+MLP(LayerNorm(x))+Attention(LayerNorm(x))\text{Parallel: }\ y = x + \mathrm{MLP}\bigl(\mathrm{LayerNorm}(x)\bigr) + \mathrm{Attention}\bigl(\mathrm{LayerNorm}(x)\bigr)

The parallel form is faster because the input matrix multiplications of the feed-forward network and attention can be fused. In the paper's experiments, quality dropped slightly for the 8 billion model but not for the 62 billion model, so the authors adopted it on the expectation that it would have no effect at 540 billion either.

The SwiGLU feed-forward network in item 1 is given by the following equation (⊗\otimes is the element-wise product).

FFNSwiGLU(x)=(Swish(xW)⊗xV) W2\mathrm{FFN}_{\mathrm{SwiGLU}}(x) = \bigl(\mathrm{Swish}(xW) \otimes xV\bigr)\, W_2

The paper trained three models of different sizes on the same data in the same way (Table 1 of the paper). The intermediate size of the feed-forward network is 4×dmodel4 \times d_{\text{model}}, and the head size is 256 in all of them.

ModelLayersHeadsdmodeld_{\text{model}}ParametersBatch (sequences)
PaLM 8B321640968.63B256 → 512
PaLM 62B6432819262.50B512 → 1024
PaLM 540B1184818432540.35B512 → 1024 → 2048

Training: data, Pathways, and settings

The training data consists of 780 billion tokens of high-quality text, and every model uses it exactly once (1 epoch) (Table 2 of the paper).

DataShare
Social media conversations (multilingual)50%
Filtered web pages (multilingual)27%
Books (English)13%
GitHub code5%
Wikipedia (multilingual)4%
News (English)1%

Web pages are sampled in proportion to the score of a classifier that judges how similar they are to high-quality pages. Low-scoring pages are not removed completely. The code consists of files in 24 programming languages (196 GB), excluding copyleft licenses and with near-duplicate files removed. Non-English text makes up about 22% of the total.

Training with Pathways: PaLM 540B was trained on two pods of 3,072 TPU v4 chips each, 6,144 chips in total. Within each pod, 12-way tensor parallelism is combined with 256-way fully sharded data parallelism, and across the two pods, data parallelism splits each batch in half. Avoiding the pipeline parallelism used by many earlier large models eliminated the idle time during which computation stalls.

The training setup (Chapter 5 of the paper) is as follows.

  • Initialization: Weights are drawn from a normal distribution whose variance shrinks with the input dimension ninn_{\text{in}} (the same idea as LeCun initialization). Embeddings use a standard normal distribution, and on the shared output side the output values are scaled by 1/n1/\sqrt{n} (nn is the embedding size)
  • Optimizer: Adafactor without matrix factorization (almost the same as Adam with the learning rate scaled by parameter magnitude). β1=0.9\beta_1 = 0.9, β2=1−k−0.8\beta_2 = 1 - k^{-0.8} (kk is the step number)
  • Learning rate: 10−210^{-2} for the first 10,000 steps, then decayed in proportion to 1/k1/\sqrt{k}
  • Gradients: Clipped to a global norm of 1.0. Weight decay is the square of the current learning rate
  • Loss: The language modeling loss without label smoothing, plus an auxiliary loss 10−4⋅log⁡2Z10^{-4} \cdot \log^2 Z (z-loss) that pushes the softmax normalizer ZZ toward 1
  • Length and batch: 2048 tokens. For 540B, the batch starts at 512 sequences (1 million tokens), increases to 1,024 at 50,000 steps and to 2,048 (4 million tokens) at 115,000 steps, and training ends at 255,000 steps
  • Dropout: Not used in pretraining (typically 0.1 in fine-tuning)

The batch size grows during training because, early on, smaller batches reduce the loss with fewer tokens, while later on, larger batches give more accurate gradient estimates. Larger batches also make the matrix multiplications bigger, so the TPUs are used more efficiently.

Why scaling up makes reasoning tasks solvable

Earlier work (for example, Gopher) had found that tasks requiring many steps of reasoning, such as math and logic, improve little as models grow. The PaLM paper showed that combining scale with chain-of-thought prompting breaks through this wall.

Chain-of-thought prompting is a method of writing not only the answer but also the intermediate reasoning in the few-shot examples.

  • Example question: "Roger has 5 tennis balls. He buys 2 cans of 3 tennis balls each. How many does he have now?"
  • Example answer: "He starts with 5. 2 cans of 3 balls each is 6. 5 + 6 = 11. The answer is 11."

The model then writes its intermediate reasoning in the same form for a new question before answering. The difficulty of math word problems lies less in the arithmetic itself than in turning the text into equations. Having the model write its intermediate reasoning lets it break the problem into small steps rather than producing the answer in one go. It is like solving a problem on paper, writing out the intermediate steps, instead of doing it in one's head.

However, the effect of this method only appeared in large models. On GSM8K, PaLM 540B scored 58% with chain of thought and 17% without it. The paper examined 45 of the 150 problems that the 62 billion model got wrong and showed that most of the errors, "semantic misunderstanding," "one step missing," and "other," were fixed by scaling to 540 billion.

In addition, on about 25% of the BIG-bench tasks, discontinuous improvements were observed, where the gain from 62 billion to 540 billion was much larger than from 8 billion to 62 billion. For example, the (normalized) accuracy on a task asking for logical sequence was 13% at 8 billion, 25% at 62 billion, and 87% at 540 billion. Extrapolating the gain from 8 billion to 62 billion would predict 37%, so the result exceeds that by 50 points. The paper suggests that some abilities only emerge once a certain scale is reached.

On many tasks, the improvement was not discontinuous but rose smoothly in proportion to the logarithm of the parameter count (the gains from 8 billion to 62 billion and from 62 billion to 540 billion were about the same). Since this improvement has not yet plateaued, the paper states that performance would rise further with even larger models.

Experimental results

29 English tasks (PaLM 540B vs. the previous best of large language models; the number of few-shot examples varies by task; excerpt from Table 4 of the paper)

TaskPrevious best (few-shot)PaLM 540B (few-shot)
TriviaQA (exact match)75.881.4
Natural Questions (exact match)32.539.6
LAMBADA (exact match)87.289.7
HellaSwag82.483.8
WinoGrande79.285.1
DROP (F1)58.670.8
SQuAD v2 (F1)71.883.3
ARC-c52.065.9
BoolQ84.889.1
ANLI R144.356.9

Of the 29 tasks, PaLM surpassed the previous best on 24 in the one-shot setting and 28 in the few-shot setting. It outperformed Megatron-Turing NLG 530B, a model of similar size, on every task, and the paper attributes this not only to scale but also to the training data, training method, and number of training tokens.

MMLU (5-shot, accuracy %; Table 6 of the paper)

ModelAverageHumanitiesSTEMSocial sciencesOther
Chinchilla 70B (previous best)67.563.654.979.373.9
PaLM 62B53.759.541.962.755.8
PaLM 540B69.377.055.681.069.6

Math word problems: GSM8K (8-shot, accuracy %; Table 10 of the paper)

MethodAccuracy
PaLM 540B + chain of thought + calculator58
PaLM 540B (no chain of thought)17
GPT-3 + fine-tuning + chain of thought + calculator + answer verifier55
GPT-3 + fine-tuning + chain of thought + calculator34

The calculator only evaluates the generated equations externally. According to the paper, the calculator improved results by 5% or less on every dataset. PaLM reached the state of the art on 4 of 7 reasoning datasets and came close on the other 3.

Code (pass@1 is the percentage of single generations that pass the tests; Table 12 of the paper)

TaskPaLM 540BCodex 12BPaLM-Coder 540B
HumanEval (zero-shot)26.228.836.0
MBPP (3-shot)36.8-47.0

Although only 5% of PaLM's training data is code, it came close to Codex 12B, which was trained specifically on code. PaLM-Coder is PaLM further fine-tuned on code.

Practical considerations

Keep the following points in mind when building or using a large language model such as PaLM.

  • It memorizes training data: Given the first 50 tokens of some sentences from the training data, the 540 billion model reproduced the next 50 tokens verbatim 2.4% of the time (1.6% for 8 billion). If personal information or copyrighted works are in the training data, the model may output them.
  • Bias and toxicity: When continuing sentences about religion, race, and gender, the model sometimes generated stereotypes, for example associating Muslims with terrorism and violence, and this was seen at every size. The toxicity of generated text was also strongly pulled along by the toxicity of the input text.
  • Overlap with evaluation data: Chapter 8 of the paper examines the overlap between training and evaluation data. Models trained on web text may have trained on evaluation data.
  • Chain of thought works in large models: Using the same prompts with small models should not be expected to have the same effect.

During the training of PaLM 540B, the loss suddenly spiked about 20 times, even with gradient clipping. This did not happen in smaller models. The paper worked around it by restarting training from a checkpoint about 100 steps before the spike and skipping roughly 200 to 500 batches around it. Since the same batches did not cause spikes when trained with weights from a different point, the spikes are thought to arise not from bad data itself but from the combination of particular data with particular weights. When training large models, it is important to save checkpoints frequently.

Comparison with other models

The following table compares PaLM with large language models of the same period from the same viewpoints (parameter counts, token counts, and training compute are from Table 21 of the PaLM paper and each model's paper; compute is counted as 6×6 \times parameters ×\times tokens; MMLU is 5-shot).

ModelParametersTraining tokensTraining compute (zettaFLOPs)Architectural featuresMMLU
GPT-3175B300B-Alternates dense and banded sparse attention43.9
Gopher280B300B504.0RMSNorm, relative position encoding60.0
Chinchilla70B1.4T588.0Same as Gopher67.5
PaLM 62B62.5B795B295.7SwiGLU, parallel layers, MQA, RoPE53.7
PaLM 540B540B780B2,527.2Same as above69.3

PaLM 540B used more than 4 times the compute of Chinchilla and outperformed it by about 2 points on MMLU. Chapter 13 of the paper states that it is not yet known whether, at the same compute, it would have been better to train a smaller model for longer (for example, a 62 billion model on 7 trillion tokens). In comparisons with Chinchilla, Chinchilla lies slightly above PaLM's scale-versus-performance curve on BIG-bench and slightly below it on 9 English tasks.

Among PaLM's architectural choices, SwiGLU was also adopted by LLaMA (the LLaMA paper states that it followed PaLM in using SwiGLU).

Rough guidelines for choosing:

  • Solving tasks that require reasoning with prompts alone: As the PaLM paper showed, combining a large model with chain-of-thought prompting is effective.
  • Designing the architecture of a large language model: PaLM's changes (SwiGLU, parallel layers, multi-query attention, RoPE, no biases) are useful references as components that improve training speed, stability, and inference cost, respectively.
  • Running a model locally: PaLM's weights are not publicly available. Open models that use SwiGLU and RoPE, such as LLaMA and Llama 2, are better suited.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F

"""
A small example of the PaLM decoder layer (Chapter 2 of the paper)
  - Parallel layer: y = x + Attention(LayerNorm(x)) + MLP(LayerNorm(x))
  - Multi-query attention: queries per head, one set of keys and values shared by all heads
  - SwiGLU feed-forward: (Swish(xW) * xV) W2
  - RoPE: rotate queries and keys by angles proportional to position
  - No biases (fully connected layers and layer normalization)
PaLM uses no dropout in pretraining, so model.train() and model.eval() compute the same thing
"""

def rope(x, theta=10000.0):
  # x: [batch, heads, seq, head_dim]. Rotate each pair of dimensions by an angle proportional to position m
  b, h, n, d = x.shape
  freqs = 1.0 / (theta ** (torch.arange(0, d, 2, device=x.device).float() / d))
  ang = torch.outer(torch.arange(n, device=x.device).float(), freqs)      # [seq, d/2]
  cos, sin = ang.cos(), ang.sin()
  x1, x2 = x[..., 0::2], x[..., 1::2]
  return torch.stack([x1 * cos - x2 * sin, x1 * sin + x2 * cos], dim=-1).flatten(-2)


class PaLMBlock(nn.Module):
  def __init__(self, d_model, n_heads, head_dim=256):
    super().__init__()
    self.h, self.hd = n_heads, head_dim
    self.norm = nn.LayerNorm(d_model, bias=False)                         # No bias (PyTorch 2.1 or later)
    self.q = nn.Linear(d_model, n_heads * head_dim, bias=False)           # Queries: [k, h]
    self.kv = nn.Linear(d_model, 2 * head_dim, bias=False)                # Keys and values: only one set of [1, h]
    self.o = nn.Linear(n_heads * head_dim, d_model, bias=False)
    self.w = nn.Linear(d_model, 4 * d_model, bias=False)                  # Gate side of SwiGLU
    self.v = nn.Linear(d_model, 4 * d_model, bias=False)
    self.w2 = nn.Linear(4 * d_model, d_model, bias=False)

  def forward(self, x):
    b, n, _ = x.shape
    h = self.norm(x)                                                      # One normalization used by both branches
    # --- Multi-query attention ---
    q = self.q(h).view(b, n, self.h, self.hd).transpose(1, 2)             # [b, heads, n, hd]
    k, v = self.kv(h).view(b, n, 2, 1, self.hd).unbind(2)                 # each [b, n, 1, hd]
    k, v = k.transpose(1, 2), v.transpose(1, 2)                           # [b, 1, n, hd]
    q, k = rope(q), rope(k)
    k, v = k.expand(-1, self.h, -1, -1), v.expand(-1, self.h, -1, -1)      # All heads use the same keys and values
    a = F.scaled_dot_product_attention(q, k, v, is_causal=True)           # Mask future positions
    attn = self.o(a.transpose(1, 2).reshape(b, n, -1))
    # --- SwiGLU feed-forward ---
    mlp = self.w2(F.silu(self.w(h)) * self.v(h))                          # Swish (β = 1) = SiLU
    return x + attn + mlp                                                 # Parallel layer: sum the three


block = PaLMBlock(d_model=512, n_heads=4, head_dim=64)
x = torch.randn(2, 16, 512)
print(block(x).shape)                                                     # torch.Size([2, 16, 512])

# z-loss (Chapter 5 of the paper): auxiliary loss that pushes the softmax normalizer log Z toward 0
def lm_loss_with_z(logits, targets, z_coef=1e-4):
  log_z = torch.logsumexp(logits, dim=-1)                                 # log Z
  ce = F.cross_entropy(logits.flatten(0, 1), targets.flatten())           # No label smoothing
  return ce + z_coef * (log_z ** 2).mean()

FAQ

Q. What are PaLM's "parallel layers"?
A.

In a standard Transformer layer, the attention output is added first, and the result is then fed into the feed-forward network. PaLM feeds the same normalized input LayerNorm(x)\mathrm{LayerNorm}(x) into attention and the feed-forward network simultaneously, computing y=x+Attention(LayerNorm(x))+MLP(LayerNorm(x))y = x + \mathrm{Attention}(\mathrm{LayerNorm}(x)) + \mathrm{MLP}(\mathrm{LayerNorm}(x)). Because the two input matrix multiplications can be fused, training is about 15% faster for large models. In the paper's experiments, quality did not drop for the 62 billion model.

Q. What is chain-of-thought prompting?
A.

It is a method of writing not only the answers but also the intermediate reasoning in the few-shot examples, so that the model also writes out intermediate steps before answering. With this method, PaLM 540B's accuracy on the GSM8K math word problems rose from 17% to 58%. The effect appears in large models and is said to be hard to obtain with small models.

Q. Which is better, PaLM or Chinchilla?
A.

On MMLU (5-shot), PaLM 540B scores 69.3% and Chinchilla 70B scores 67.5%, so PaLM is slightly ahead, but PaLM took more than 4 times the training compute. The PaLM paper itself states that it is not yet known whether training a smaller model for longer at the same compute would have been better. Since the cost of use scales with model size, the 70 billion Chinchilla is cheaper to use.

References

  1. Chowdhery, A., Narang, S., Devlin, J., et al. (2022). PaLM: Scaling Language Modeling with Pathways. arXiv:2204.02311.
  2. Shazeer, N. (2020). GLU Variants Improve Transformer. arXiv:2002.05202.
  3. Shazeer, N. (2019). Fast Transformer Decoding: One Write-Head is All You Need. arXiv:1911.02150.
  4. Su, J., Lu, Y., Pan, S., Murtadha, A., Wen, B., & Liu, Y. (2021). RoFormer: Enhanced Transformer with Rotary Position Embedding. arXiv:2104.09864.
  5. Wei, J., Wang, X., Schuurmans, D., et al. (2022). Chain-of-Thought Prompting Elicits Reasoning in Large Language Models. NeurIPS 2022.
  6. Hoffmann, J., Borgeaud, S., Mensch, A., et al. (2022). Training Compute-Optimal Large Language Models. arXiv:2203.15556.