AI Logic

Architectures

GPT (Generative Pre-Training)

Updated:

Structure of GPT. Left: the overall flow (token and position embeddings, repeated decoder layers, and two outputs: next-token prediction for pre-training and classification for fine-tuning) 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)

Background and overview

GPT (Generative Pre-Training) is a method and model that pre-trains a stack of Transformer decoders on unlabeled text by "next-word prediction" and then fine-tunes it for each task. It was proposed by Radford et al. at OpenAI in 2018 in the technical report "Improving Language Understanding by Generative Pre-Training." It is the starting point for the later GPT-2 and GPT-3.

Tasks such as natural language inference and question answering had little labeled data, and models trained from scratch for each task struggled to improve. Unlabeled text, on the other hand, is plentiful. GPT bridged this gap in the following two stages.

  1. Generative pre-training: train a language model that predicts the next word from the previous words on a large amount of text.
  2. Discriminative fine-tuning: add one output layer and retrain the whole model on the task's labeled data.

Another feature is that, instead of rebuilding the model architecture for each task, it uses "input transformations" that rearrange sentence pairs or answer choices into a single token sequence, so the same model can be used for many tasks.

In the paper, it achieved state-of-the-art results at the time on 9 of 12 tasks. It surpassed previous results by 8.9 points on commonsense reasoning (Story Cloze), 5.7 points on question answering (RACE), and 1.5 points on natural language inference (MultiNLI), and raised the GLUE score from 68.9 to 72.8.

Architecture

GPT removes the "attention over the encoder output" from the Transformer decoder layer and stacks 12 layers consisting only of self-attention that masks future words and a feed-forward network. The left side of the figure at the top of the article shows the overall flow of pre-training and fine-tuning and the range attention can see, and the right side shows the inside of one decoder layer.

The computation from input to output is expressed by the following equations.

h0=UWe+Wphl=transformer_block(hlāˆ’1)(l=1,…,n)P(u)=softmax(hnWe⊤)\begin{aligned} h_0 &= U W_e + W_p \\ h_l &= \mathrm{transformer\_block}(h_{l-1}) \qquad (l = 1, \dots, n) \\ P(u) &= \mathrm{softmax}(h_n W_e^\top) \end{aligned}

Here, UU is the preceding kk tokens (the context), WeW_e is the token embedding matrix, WpW_p is the position embedding matrix, and nn is the number of layers. The last equation multiplies by the transpose of the same matrix WeW_e used for the input embeddings to produce the probability that each token in the vocabulary comes next.

The settings in the paper are as follows.

ItemValue
Layers12
Vector length768
Heads12
Feed-forward inner size3072
Context length512 tokens
TokenizationBPE (40,000 merges)
Positional representationLearned positional embeddings (not the sinusoids of the original Transformer)
Activation functionGELU

Each token sees only itself and the tokens to its left. This is because, when computing attention weights, the values at positions to the right are set to āˆ’āˆž-\infty before applying softmax (masking). This way, training to "predict the next token from the text up to that position" happens at every position simultaneously within a single sequence.

As in the original Transformer, layer normalization comes after the residual addition (Post-LN). GPT-2 moves it to the input side of each sublayer (Pre-LN; see Pre-LN and Post-LN).

Training

In pre-training, the following log-likelihood is maximized over an unlabeled token sequence U={u1,…,un}\mathcal{U} = \{u_1, \dots, u_n\} (kk is the context length and Θ\Theta the model's weights).

L1(U)=āˆ‘ilog⁔P(ui∣uiāˆ’k,…,uiāˆ’1;Θ)L_1(\mathcal{U}) = \sum_i \log P(u_i \mid u_{i-k}, \dots, u_{i-1}; \Theta)

This is the same as minimizing the cross-entropy loss of predicting the next token at each position.

ItemValue
DataBooksCorpus (over 7,000 unpublished books, including long stretches of contiguous text)
Batch64 contiguous sequences of 512 tokens
Epochs100
OptimizerAdam (maximum learning rate 2.5Ɨ10āˆ’42.5 \times 10^{-4})
Learning rateIncreased linearly from 0 over the first 2,000 updates (warmup), then annealed to 0 with a cosine schedule
Weight initializationNormal distribution with mean 0 and standard deviation 0.02
RegularizationDropout of 0.1 on residuals, embeddings, and attention; weight decay in the style of AdamW (w=0.01w = 0.01, excluding biases and gains)

The trained language model achieved a token-level perplexity of 18.4 on this corpus.

In fine-tuning, a dataset C\mathcal{C} of pairs of input token sequences x1,…,xmx^1, \dots, x^m and labels yy is used. A new linear layer WyW_y is applied to the output hlmh_l^m of the last token in the last layer to predict the label.

P(y∣x1,…,xm)=softmax(hlmWy),L2(C)=āˆ‘(x,y)log⁔P(y∣x1,…,xm)P(y \mid x^1, \dots, x^m) = \mathrm{softmax}(h_l^m W_y), \qquad L_2(\mathcal{C}) = \sum_{(x, y)} \log P(y \mid x^1, \dots, x^m)

The paper reports that adding the language modeling loss as an auxiliary objective during fine-tuning also improves generalization and speeds up convergence.

L3(C)=L2(C)+λ⋅L1(C),Ī»=0.5L_3(\mathcal{C}) = L_2(\mathcal{C}) + \lambda \cdot L_1(\mathcal{C}), \qquad \lambda = 0.5

The fine-tuning settings are a learning rate of 6.25Ɨ10āˆ’56.25 \times 10^{-5}, a batch size of 32, 3 epochs for most tasks, warmup over 0.2% of training followed by linear decay, and dropout of 0.1 on the classifier. The only new weights are WyW_y and the embeddings of the delimiter tokens.

Input transformations arrange structured inputs into a single sequence. For every task, start ⟨s⟩ and end ⟨e⟩ tokens are added.

  • Natural language inference: the premise and hypothesis are concatenated with a delimiter token ($) between them.
  • Sentence similarity: since the two sentences have no inherent order, sequences in both orders are created and processed separately, and the final outputs are added element-wise before being fed to the linear layer.
  • Question answering and commonsense reasoning: for each answer choice, a sequence is built by concatenating the document and question with that choice, separated by a delimiter. Each is processed separately, and the outputs are compared with a softmax to choose the answer.

Why pre-training works

To predict the next word correctly, a model needs to know many things: grammar, word meanings, the flow of text, world knowledge, and more. The paper hypothesizes that the language model naturally acquires abilities useful for downstream tasks in order to improve its predictions, and verifies this with the following two analyses.

  • Transferring more layers helps: when fine-tuning with gradually more pre-trained layers transferred, from the embeddings alone up to all 12 layers, performance on MultiNLI and RACE improved with each added layer. Transferring all layers improved MultiNLI by up to 9%. This shows that every layer contains functions useful for the tasks.
  • Even without fine-tuning, the more pre-training progresses, the better the tasks are solved: the performance of simple methods that solve tasks using only the language model's probabilities (for sentiment analysis, for example, appending "very" to a sentence and judging by whether "positive" or "negative" has a higher probability as the next word) rose steadily over the course of pre-training updates.

Within the same framework, using an LSTM (1 layer, 2048 units) instead of the Transformer lowered the average score by 5.6. The paper states that the structured memory of the Transformer (the ability to look directly at distant positions with attention) helps with handling long contexts and with transfer.

Experimental results

Natural language inference (accuracy %)

ModelMNLI-mMNLI-mmSNLISciTailQNLIRTE
Previous best80.680.189.383.382.361.7
GPT82.181.489.988.388.156.0

"Previous best" is the highest value in each column of the paper's table (MNLI and SNLI include ensembles). GPT outperformed it on 4 of 5 datasets, but on RTE, which has little training data (2,490 examples), it fell short of the 61.7% of a BiLSTM trained on multiple tasks.

Question answering and commonsense reasoning (accuracy %)

ModelStory ClozeRACE-mRACE-hRACE
Previous best77.660.250.353.3
GPT86.562.957.459.0

Classification and sentence similarity (Matthews correlation for CoLA, accuracy for SST-2, F1 for MRPC and QQP, Pearson correlation for STS-B)

ModelCoLASST-2MRPCSTS-BQQPGLUE
BiLSTM + ELMo + Attn (multi-task)18.991.683.572.863.368.9
GPT45.491.382.382.070.372.8

On CoLA, which judges grammatical acceptability, the score rose sharply from the previous best of 35.0 to 45.4.

Ablations (average score over 8 tasks)

SettingAverage
GPT (with auxiliary language modeling loss)74.7
Without auxiliary language modeling loss75.0
LSTM instead of Transformer69.1
No pre-training59.9

Without pre-training, the average score dropped by 14.8. The auxiliary loss made almost no difference on average, but it tended to help on large datasets such as natural language inference and QQP and not on small ones.

Caveats when using it

When using the ideas of GPT or reading its results, keep the following points in mind.

  • Only the left context can be used: since each token cannot see to its right, the representation of a word in the middle of a sentence contains no information from later words. The BERT paper showed that making a model of the same size bidirectional greatly improves token-level tasks such as question answering.
  • Input transformations and delimiter tokens are required: for tasks involving sentence pairs or answer choices, inputs must be arranged into a single sequence in the paper's format, and the embeddings of the delimiter tokens must be newly learned.
  • Context is limited to 512 tokens: position embeddings are learned only up to position 512.
  • It may not be strong on small data: on tasks with little training data, such as RTE, it fell short of earlier methods. The auxiliary language modeling loss was also ineffective on small datasets.

If the mask that hides future tokens is forgotten, each position can see the next token, which is the "answer," during training. The loss then drops easily, but the model cannot predict anything when actually generating word by word. When implementing it yourself, always apply an upper-triangular mask to attention (causal_mask in the implementation example below).

Comparison with other models

Comparing pre-trained language models from the same viewpoints gives the following.

ModelArchitecturePre-training taskPre-training dataUse on downstream tasks
ELMoBidirectional LSTMLanguage model (each direction separately)1B Word Benchmark (shuffled at the sentence level)Outputs are fed as features into a task-specific model
GPTTransformer decoder only (12 layers)Language model (left to right)BooksCorpusFine-tune the whole model
BERTTransformer encoder onlyMasked language model + next sentence predictionBooksCorpus + WikipediaFine-tune the whole model
GPT-2Transformer decoder only (up to 48 layers)Language model (left to right)WebText (about 8 million documents)Tasks instructed in the input text, without fine-tuning

The paper notes that the 1B Word Benchmark used by ELMo is shuffled at the sentence level, destroying long-range structure, whereas BooksCorpus contains long stretches of contiguous text, which makes it possible to learn long contexts.

Rough guidelines for choosing are as follows.

  • To generate text: decoder-only models of the GPT family are a good fit. Predicting one word at a time from the left can be used directly for generation.
  • For sentence classification or per-word predictions within a sentence: models of the BERT family, which can use context in both directions, are a good fit.
  • When fine-tuning data cannot be prepared: consider instructing tasks in the input text, as with GPT-2 and GPT-3, which were trained on larger data.

PyTorch example

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

"""
A small implementation that follows the equations of GPT (Radford et al. 2018)
  h_0 = U W_e + W_p, h_l = transformer_block(h_{l-1}), P(u) = softmax(h_n W_e^T)
  Pre-training: L1 (next-token prediction). Fine-tuning: L3 = L2 + Ī» L1
"""

vocab_size = 1000     # The paper uses BPE with 40,000 merges
context = 64          # 512 in the paper
d_model = 128         # 768 in the paper
n_head = 4            # 12 in the paper
n_layer = 4           # 12 in the paper
dropout = 0.1

device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'


class Block(nn.Module):
  """Decoder layer: masked self-attention → feed-forward (Post-LN: normalize after adding the residual)"""
  def __init__(self):
    super().__init__()
    self.attn = nn.MultiheadAttention(d_model, n_head, dropout=dropout, batch_first=True)
    self.ln1 = nn.LayerNorm(d_model)
    self.ffn = nn.Sequential(nn.Linear(d_model, 4 * d_model), nn.GELU(),
                             nn.Linear(4 * d_model, d_model), nn.Dropout(dropout))
    self.ln2 = nn.LayerNorm(d_model)
    self.drop = nn.Dropout(dropout)

  def forward(self, x, causal_mask):
    a, _ = self.attn(x, x, x, attn_mask=causal_mask, need_weights=False)
    x = self.ln1(x + self.drop(a))
    return self.ln2(x + self.ffn(x))


class GPT(nn.Module):
  def __init__(self, num_labels=2):
    super().__init__()
    self.W_e = nn.Embedding(vocab_size, d_model)     # Token embeddings
    self.W_p = nn.Embedding(context, d_model)        # Learned position embeddings
    self.drop = nn.Dropout(dropout)
    self.blocks = nn.ModuleList([Block() for _ in range(n_layer)])
    self.W_y = nn.Linear(d_model, num_labels)        # Linear layer added for fine-tuning
    for p in self.parameters():                      # Paper: initialize with N(0, 0.02)
      if p.dim() > 1:
        nn.init.normal_(p, mean=0.0, std=0.02)

  def forward(self, u):                              # u: [B, T]
    T = u.size(1)
    # True positions cannot be attended to: an upper-triangular mask hiding positions to the right (the future)
    causal_mask = torch.triu(torch.ones(T, T, dtype=torch.bool, device=u.device), diagonal=1)
    h = self.drop(self.W_e(u) + self.W_p(torch.arange(T, device=u.device)))
    for block in self.blocks:
      h = block(h, causal_mask)
    lm_logits = h @ self.W_e.weight.T                # h_n W_e^T (reuses the embedding matrix)
    cls_logits = self.W_y(h[:, -1])                  # Predict the label from the last token's output
    return lm_logits, cls_logits


def lm_loss(lm_logits, u):
  # Predict the token at position i+1 from the output at position i (the mean of L1 with its sign flipped)
  return F.cross_entropy(lm_logits[:, :-1].reshape(-1, vocab_size), u[:, 1:].reshape(-1))


model = GPT().to(device)
optimizer = torch.optim.AdamW(model.parameters(), lr=2.5e-4, weight_decay=0.01)

# One pre-training step (random token sequences here; large amounts of text in practice)
model.train()
u = torch.randint(0, vocab_size, (8, context), device=device)
lm_logits, _ = model(u)
loss = lm_loss(lm_logits, u)
loss.backward()
optimizer.step()
optimizer.zero_grad()

# One fine-tuning step: L3 = L2 + Ī» L1 (Ī» = 0.5)
x = torch.randint(0, vocab_size, (8, context), device=device)   # Sequence arranged like ⟨s⟩ sentence $ sentence ⟨e⟩
y = torch.randint(0, 2, (8,), device=device)
lm_logits, cls_logits = model(x)
loss = F.cross_entropy(cls_logits, y) + 0.5 * lm_loss(lm_logits, x)
loss.backward()
optimizer.step()
optimizer.zero_grad()

# Generation: predict one token at a time and append it (greedy decoding)
model.eval()
with torch.no_grad():
  seq = torch.randint(0, vocab_size, (1, 5), device=device)
  for _ in range(20):
    lm_logits, _ = model(seq[:, -context:])
    next_token = lm_logits[:, -1].argmax(dim=-1, keepdim=True)
    seq = torch.cat([seq, next_token], dim=1)
print(seq.tolist())

FAQ

Q. Why is GPT called "decoder-only"?
A.

The decoder of the original Transformer uses self-attention that masks future words, predicting the next word by looking only at the words generated so far. GPT stacks only these masked self-attention and feed-forward layers and has neither an encoder nor attention over an encoder's output, hence the name.

Q. What is the difference between GPT and BERT?
A.

GPT is pre-trained as a language model that predicts the next word from left to right, and each word sees only the words to its left. BERT is pre-trained as a masked language model that predicts hidden words from the context on both sides, and each word sees everything before and after it. BERT-Base was given the same size as GPT for comparison, and the differences are the attention mask and the pre-training task.

Q. Why is the language modeling loss also added during fine-tuning?
A.

According to the paper, adding the auxiliary loss λL1\lambda L_1 improved generalization and sped up convergence. It is thought to prevent the weights from shifting too far toward label prediction alone, which would erode the linguistic knowledge acquired in pre-training. However, in the paper's comparison, it helped only on tasks with large datasets and had no effect on small ones.

References

  1. Radford, A., Narasimhan, K., Salimans, T., & Sutskever, I. (2018). Improving Language Understanding by Generative Pre-Training. OpenAI.
  2. Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., Kaiser, Ł., & Polosukhin, I. (2017). Attention Is All You Need. NIPS 2017.
  3. Radford, A., Wu, J., Child, R., Luan, D., Amodei, D., & Sutskever, I. (2019). Language Models are Unsupervised Multitask Learners. OpenAI.
  4. Devlin, J., Chang, M.-W., Lee, K., & Toutanova, K. (2019). BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding. NAACL-HLT 2019. arXiv:1810.04805.