GPT Architecture
Prerequisites
- Large Language Models — pretraining, scaling
- Language Models — autoregressive prediction
🎯 Learning Objectives
- Describe the decoder-only transformer architecture used by GPT
- Explain autoregressive generation (next-token prediction)
- Trace the progression from GPT-1 through GPT-4
- Understand BPE tokenization and its role in GPT
- Explain positional encoding and causal masking
1. Decoder-Only Transformer
The original Transformer (Vaswani et al., 2017) has an encoder-decoder architecture. GPT uses only the decoder stack, modified with causal (left-to-right) attention.
Architecture of a single GPT block:
- Masked Multi-Head Self-Attention: Each position can only attend to itself and previous positions (causal mask prevents looking ahead).
- Layer Normalization: Applied before each sub-layer (pre-norm in GPT-2+).
- Feed-Forward Network (FFN): Two linear layers with a GELU activation: FFN(x) = W₂ · GELU(W₁ · x + b₁) + b₂.
- Residual Connections: Each sub-layer adds its input: output = x + SubLayer(LayerNorm(x)).
The full model stacks L such blocks. GPT-2 uses L = 48 layers for its largest variant; GPT-3 uses L = 96.
2. Autoregressive Generation
P(w₁, w₂, …, wT) = ∏t=1T P(wt | w₁, …, wt−1; θ)
Decoding strategies:
- Greedy decoding: Always pick the token with highest probability. Fast but can produce repetitive text.
- Beam search: Maintain top-k partial sequences at each step. Better quality but computationally expensive.
- Top-k sampling: Sample from the top k most probable tokens. Introduces diversity.
- Top-p (nucleus) sampling: Sample from the smallest set of tokens whose cumulative probability exceeds p (e.g., p = 0.9).
- Temperature: Scale logits by 1/τ before softmax. τ < 1 sharpens the distribution (more deterministic); τ > 1 flattens it (more random).
3. Causal Masking
In standard self-attention, each token attends to all positions. In GPT’s causal (masked) attention, token at position i can only attend to positions ≤ i:
Attention(Q, K, V) = softmax(QKT/√dk + M) · V
where M is a mask matrix: Mij = 0 if j ≤ i, and Mij = −∞ if j > i. The −∞ values become 0 after softmax, effectively preventing the model from “seeing the future”.
Example: Causal Mask for a 4-token sequence
| t₁ | t₂ | t₃ | t₄ | |
|---|---|---|---|---|
| t₁ | 0 | −∞ | −∞ | −∞ |
| t₂ | 0 | 0 | −∞ | −∞ |
| t₃ | 0 | 0 | 0 | −∞ |
| t₄ | 0 | 0 | 0 | 0 |
Token t₃ can attend to t₁, t₂, and t₃ (itself), but not t₄.
4. BPE Tokenization in GPT
GPT uses Byte Pair Encoding (BPE) to convert raw text into token IDs:
- Initialize: Start with a vocabulary of individual bytes (256 entries).
- Iterate: Find the most frequent pair of adjacent tokens in the training data. Merge them into a new token. Add to vocabulary.
- Repeat: Continue until the desired vocabulary size is reached (GPT-2: ~50,257 tokens).
BPE Merge Example
Corpus tokens: [l, o, w, e, r, _, l, o, w, _, n, e, w, e, s, t]
Most frequent pair: (l, o) → merge into “lo”
After merge: [lo, w, e, r, _, lo, w, _, n, e, w, e, s, t]
Next most frequent: (lo, w) → merge into “low”
After merge: [low, e, r, _, low, _, n, e, w, e, s, t]
This process continues until the target vocabulary size is reached.
Advantages: Handles out-of-vocabulary words (falls back to subwords/bytes), compact vocabulary, language-agnostic.
5. Positional Encoding
Transformers have no inherent notion of sequence order (unlike RNNs). Positional information must be explicitly injected.
5.1 Learned Positional Embeddings (GPT-1/2/3)
GPT learns a position embedding matrix P ∈ ℝTmax × d where Tmax is the maximum sequence length. The input to the first block is:
h₀ = We · x + P[1:T]
where We is the token embedding matrix and P[1:T] selects the first T position embeddings.
5.2 Sinusoidal Encoding (Original Transformer)
The original Transformer used fixed sinusoidal functions:
PE(pos, 2i) = sin(pos / 100002i/d)
PE(pos, 2i+1) = cos(pos / 100002i/d)
5.3 Rotary Position Embeddings (RoPE)
Modern models (Llama, GPT-NeoX) use RoPE, which encodes position by rotating the query and key vectors. This enables better extrapolation to longer sequences than learned embeddings.
6. GPT Model Progression
| Model | Year | Parameters | Layers | Context Length | Key Innovation |
|---|---|---|---|---|---|
| GPT-1 | 2018 | 117M | 12 | 512 | Unsupervised pretraining + supervised fine-tuning |
| GPT-2 | 2019 | 1.5B | 48 | 1024 | Zero-shot task transfer; no fine-tuning needed |
| GPT-3 | 2020 | 175B | 96 | 2048 | In-context few-shot learning; scaling breakthrough |
| GPT-4 | 2023 | ~1.8T* | — | 8K–128K | Multimodal (text + images); RLHF alignment |
*GPT-4 parameter count is estimated and not officially confirmed.
6.1 Key Architectural Changes Across Versions
- GPT-1 → GPT-2: Moved layer normalization before attention (pre-norm), larger context window, removed need for task-specific fine-tuning heads.
- GPT-2 → GPT-3: Massive scale increase (100× parameters), alternating dense and sparse attention layers (in some variants), demonstrated few-shot learning.
- GPT-3 → GPT-4: Mixture of Experts (MoE) architecture (rumored), multimodal input support, dramatically improved reasoning via RLHF and chain-of-thought data.
7. Summary
- GPT uses a decoder-only transformer with causal (left-to-right) masked attention.
- Autoregressive generation: P(sequence) = ∏ P(wt|w<t), one token at a time.
- Causal mask: Mij = −∞ for j > i prevents attending to future tokens.
- BPE tokenization: Iterative merging of frequent byte pairs; handles OOV words.
- Positional encoding: Learned (GPT-1/2/3) or rotary (modern variants).
- Progression: GPT-1 (117M) → GPT-2 (1.5B) → GPT-3 (175B) → GPT-4 (~1.8T).