βοΈ GPT: Generative Pre-Training
GPT: Generative Pre-Training (Radford et al., 2018)
Improving Language Understanding by Generative Pre-Training made a simple bet. Labelled data is scarce and unlabelled text is nearly free, so first train a transformer to predict the next token on a large pile of books. Then adapt it to each real task with a small labelled set and a thin output layer.
The model is the Transformer decoder from Attention Is All You Need with the encoder and cross-attention removed. The method is two stages, and every GPT since has kept that shape:
- Unsupervised pre-training: maximise $\sum_i \log P(u_i \mid u_{i-k}, \dots, u_{i-1})$ on raw text.
- Supervised fine-tuning: add a linear layer, train on the task, and keep the language-modelling loss as an auxiliary term.
This page trains a tiny GPT for real, generates from it, checks the causal mask, counts GPT-1's 117M parameters from its configuration, and tests the paper's central claim: features learned by next-token prediction transfer to a task the model was never trained on.
helpers ready
1. A corpus with structure to learn
GPT-1 pre-trained on BooksCorpus, about 7,000 unpublished books. Here the corpus is generated from a small grammar instead: subjects, verbs, objects, places and connectives combined at random. It has real structure, such as agreement, word order and punctuation, and it is small enough to learn in seconds on a CPU.
The model reads characters, not BPE tokens, so the vocabulary is tiny and nothing hides in the tokenizer.
============================================================================== BUILD THE CORPUS ============================================================================== 119,257 characters, vocabulary of 25: ' .abcdefghiklmnoprstuvwxy' sample: 'my sister follows the small house in the morning. the dog likes a green tree. a bird follows her friend in the morning. a child watches a red box. the' Baselines: how predictable is the next character without a neural net? ------------------------------------------------------------------------------ unigram (letter frequencies only): 2.747 nats per character bigram (previous character only): 1.615 nats per character
2. A decoder-only transformer, and its training objective
The architecture is the GPT-1 recipe at toy scale: token and learned position embeddings, a stack of blocks (masked self-attention then a feed-forward layer, each wrapped in a residual connection and layer norm), and an output layer that shares its weights with the token embedding.
The loss is the paper's $L_1$: the average negative log-probability of each next character. One forward pass over a 64-character window gives 64 predictions at once, because the causal mask stops each position from seeing its future.
============================================================================== PRE-TRAIN WITH THE LANGUAGE-MODELLING LOSS ============================================================================== parameters: 344,064 step 1: train 3.312 validation 3.004 nats/char step 100: train 1.085 validation 1.098 nats/char step 300: train 0.305 validation 0.304 nats/char step 700: train 0.262 validation 0.265 nats/char Compare with the baselines ------------------------------------------------------------------------------ unigram 2.747 bigram 1.615 tiny GPT 0.265 [PASS] the transformer beats the bigram model on held-out text
3. The causal mask, verified on the trained model
The loss above is valid only if position $t$'s prediction does not depend on characters after $t$. Otherwise the model could read the answer. The check: change the last half of an input and confirm that the first half's outputs do not move at all.
============================================================================== THE FUTURE CANNOT LEAK INTO THE PAST ============================================================================== max change in logits at positions 0-31: 0.00e+00 max change in logits at positions 32-63: 21.91 [PASS] earlier predictions untouched by later characters
4. Generation is the training objective, run in a loop
To generate, predict a distribution for the next character, pick one, append it, and repeat. The animation below runs exactly that on the model trained above. The bars are its real top-5 probabilities at each step, sampled with temperature 0.7.
============================================================================== SAMPLING FROM THE TRAINED MODEL ============================================================================== prompt: 'the dog ' output: 'the dog watches her friend aft' step 1: top-5 = ['f' 0.41, 'h' 0.18, 'l' 0.17, 'w' 0.14, 's' 0.09] -> picked 'w' step 2: top-5 = ['a' 1.00, 's' 0.00, 'o' 0.00, 't' 0.00, 'n' 0.00] -> picked 'a' step 3: top-5 = ['t' 1.00, 'f' 0.00, 'c' 0.00, 'n' 0.00, ' ' 0.00] -> picked 't' step 4: top-5 = ['c' 1.00, 'b' 0.00, 't' 0.00, 'h' 0.00, ' ' 0.00] -> picked 'c' step 5: top-5 = ['h' 1.00, 's' 0.00, 'f' 0.00, 'a' 0.00, 'w' 0.00] -> picked 'h' step 6: top-5 = ['e' 1.00, ' ' 0.00, 'k' 0.00, 'h' 0.00, 'i' 0.00] -> picked 'e' Two longer samples ------------------------------------------------------------------------------ 'a child helps her friend. the old man helps the small house. the dog' 'my sister likes the river near the river. the old man follows her friend in '
5. GPT-1's size, counted from its configuration
The paper's model: 12 decoder blocks, $d = 768$, 12 heads, feed-forward width 3,072, learned position embeddings for 512 positions, and a BPE vocabulary with 40,000 merges (40,478 tokens in the released model). The output layer is tied to the token embedding, so it adds no parameters.
============================================================================== COUNTING GPT-1 ============================================================================== token embedding 40,478 x 768 = 31,087,104 position emb. 512 x 768 = 393,216 attention / block 4*768^2 + 4*768 = 2,362,368 MLP / block 2*768*3072 + 3072 + 768 = 4,722,432 layer norms/block 2 x (gain + bias) = 3,072 12 blocks = 85,054,464 total = 116,534,784 (116.5M) The usual figure is 117M; the GPT-2 paper lists its smallest model, the same shape as GPT-1, at that size. Count here: 116.5M. Our tiny model, counted the same way vs PyTorch ------------------------------------------------------------------------------ [PASS] formula 344,064 == PyTorch 344,064
6. Fine-tuning: one model, many task formats
The second stage adds one linear layer $W_y$ on the final hidden state of the last token and trains
$$L_3 = L_2(\text{task}) + \lambda\, L_1(\text{language modelling}), \qquad \lambda = 0.5$$
Keeping $L_1$ as an auxiliary loss improved generalisation and sped up convergence on the larger datasets.
The paper's other contribution is how to feed structured inputs to a model that only reads sequences. Instead of task-specific architectures, every task becomes one or more token sequences with start, delimiter and extract tokens:
7. Does pre-training transfer? A test on the tiny model
The paper's claim is that next-token prediction teaches features useful for tasks the model never saw. A small version of that test: tell a grammatical sentence from the same words in shuffled order. A bag-of-characters classifier cannot do this, because both versions contain exactly the same characters.
Two transfer methods, each given only 40 labelled examples:
- Linear probe: freeze the model, take the final hidden state at the last token (the paper's Extract position), and fit logistic regression on top. This is the cheapest form of fine-tuning.
- Zero-shot: no training at all. Score each sentence by its average LM loss and call the lower-loss one grammatical. The paper reports zero-shot heuristics like this too.
The control is the same architecture with random weights.
==============================================================================
TRANSFER WITH 40 LABELLED EXAMPLES
==============================================================================
example pair: 'the old man likes a red box near the river.'
'the red river old the near a likes box man.'
pre-trained linear probe accuracy 0.610 zero-shot pair accuracy 1.000
random init linear probe accuracy 0.508 zero-shot pair accuracy 0.623
chance level: 0.500
[PASS] pre-trained features beat random features on the probe
[PASS] zero-shot LM scoring picks the grammatical sentence far above chance
The two methods give very different results, and the difference is worth reading closely.
- Zero-shot is decisive. The pre-trained model gives the grammatical version the lower loss in every one of the 300 test pairs. With random weights that happens about 60% of the time. The signal sits directly in the language-modelling objective, because a shuffled sentence is simply less probable text.
- The linear probe is a modest win: about 61% against 51%. Forty labels and one frozen 96-dimensional state, read at the final full stop, carry only part of what the LM loss knows. The paper fine-tuned the whole model on thousands of examples, which is a much stronger form of transfer than a frozen probe.
Summary
- GPT-1 = Transformer decoder + next-token prediction on unlabelled books, then supervised fine-tuning with one added linear layer, keeping the LM loss as an auxiliary term ($\lambda = 0.5$).
- The causal mask turns one forward pass into a prediction at every position, and generation is the same prediction applied in a loop.
- Structured tasks become sequences with start, delimiter and extract tokens, so no task needs its own architecture.
- At GPT-1's configuration the parameter count comes to about 116.5M, matching the familiar "117M".
- Even at toy scale, next-token pre-training transfers. With no task training at all, its LM loss picks the grammatical sentence 100% of the time, against about 60% for random weights. A frozen linear probe on 40 labels gains less, which is why the paper fine-tunes the whole network.
- GPT-2 (2019) and GPT-3 (2020) kept this recipe, scaled it up, and found that with enough scale the fine-tuning stage could often be replaced by a prompt.