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.
Generative pre-training: train a language model that predicts the next word from the previous words on a large amount of text.
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.
Here, U is the preceding k tokens (the context), Weā is the token embedding matrix, Wpā is the position embedding matrix, and n is the number of layers. The last equation multiplies by the transpose of the same matrix Weā used for the input embeddings to produce the probability that each token in the vocabulary comes next.
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 āā 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ā} (k is the context length and Ī the model's weights).
Increased linearly from 0 over the first 2,000 updates (warmup), then annealed to 0 with a cosine schedule
Weight initialization
Normal distribution with mean 0 and standard deviation 0.02
Regularization
Dropout of 0.1 on residuals, embeddings, and attention; weight decay in the style of AdamW (w=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 of pairs of input token sequences x1,ā¦,xm and labels y is used. A new linear layer Wyā is applied to the output hlmā of the last token in the last layer to predict the label.
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.5
The fine-tuning settings are a learning rate of 6.25Ć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 Wyā and the embeddings of the delimiter tokens.
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 %)
Model
MNLI-m
MNLI-mm
SNLI
SciTail
QNLI
RTE
Previous best
80.6
80.1
89.3
83.3
82.3
61.7
GPT
82.1
81.4
89.9
88.3
88.1
56.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 %)
Model
Story Cloze
RACE-m
RACE-h
RACE
Previous best
77.6
60.2
50.3
53.3
GPT
86.5
62.9
57.4
59.0
Classification and sentence similarity (Matthews correlation for CoLA, accuracy for SST-2, F1 for MRPC and QQP, Pearson correlation for STS-B)
Model
CoLA
SST-2
MRPC
STS-B
QQP
GLUE
BiLSTM + ELMo + Attn (multi-task)
18.9
91.6
83.5
72.8
63.3
68.9
GPT
45.4
91.3
82.3
82.0
70.3
72.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)
Setting
Average
GPT (with auxiliary language modeling loss)
74.7
Without auxiliary language modeling loss
75.0
LSTM instead of Transformer
69.1
No pre-training
59.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.
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.
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ā 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.