GPT-2 is a decoder-only Transformer that generates text by predicting the next token from preceding tokens. Unlike an encoder–decoder translator, it has no encoder stack or encoder-derived inputs. Its decoder blocks use causal self-attention so generation depends on earlier tokens in the sequence. section 11.1 section 11.1.1
Figure 11.1 The architecture of the GPT-2 model. GPT-2 is a decoder-only Transformer, consisting of N identical decoder layers. Each decoder block contains two sublayers. The first sublayer is a causal self-attention layer. The second is a feed-forward network. Each sublayer uses layer normalization and a residual connection. The input is first passed through word embedding and positional encoding, and the sum is then passed through the decoder. The output from the decoder goes through layer normalization and a linear layer.
Trace token and position embeddings through repeated decoder blocks, then through the final normalization and vocabulary-output layer. section 11.1.1
A practical build follows the path from text to a next-token prediction:
- Tokenize text with byte pair encoding (BPE), then turn token indexes into learned word embeddings. For “this is a prompt,” four tokens become a 4 × 1,600 embedding matrix in GPT-2XL. section 11.1.2
- Add learned positional embeddings so the model can distinguish token order. GPT-2 supports positions in sequences of up to 1,024 tokens. section 11.1.2
- Pass the combined embeddings through decoder blocks. Each block pairs causal self-attention with a position-wise feed-forward network and uses layer normalization and residual connections. section 11.1.1
- Apply final layer normalization and a linear layer to produce an output for each of the 50,257 vocabulary tokens. section 11.1.1
Model size changes the build: GPT-2 variants have 12, 24, 36, or 48 decoder blocks. GPT-2XL uses 48 blocks, 1,600-dimensional embeddings, and about 1.5 billion parameters. Building that architecture does not train it; load released pretrained weights before using it to generate meaningful text. section 11.1.1 section 11.3
A smaller model for training practice
A simplified, 5.12-million-parameter GPT-2-style model can instead be trained on three novels. Generating from “the old man saw the shark near the” makes a useful check: compare coherence with passages copied from training data. In this example, the 20-epoch model is less coherent than the 40-epoch model but has a lower risk of copying. section 12.4 section 12.4.3





