Pass 1: Model Core
- Decoder-only architecture
- Causal masking and token-by-token prediction
- BPE tokenization and context windows
OpenAI's generative model that showed language models can perform tasks they were never explicitly trained for — from translation to summarization — by scaling autoregressive next-token prediction.
Read this chapter in three passes: start with objective and masking, then move to generation controls, then finish with serving and reliability patterns.
GPT-2 models language as a left-to-right factorization over tokens. Every capability emerges from this one objective when model scale and data scale are large enough.
This makes decoding straightforward at inference time and naturally supports prompting, in-context learning, and zero-shot behavior.
While BERT asked "Can we understand language by predicting masked words?", GPT asked a fundamentally different question: "Can we learn everything just by predicting the next word?"
GPT-2 demonstrated that a large enough language model, trained on enough data, can perform tasks it was never explicitly trained for — translation, summarization, question answering — in a zero-shot setting.
BERT = Encoder-only, bidirectional, requires task-specific fine-tuning.
GPT-2 = Decoder-only, unidirectional (left-to-right), performs tasks via prompting without fine-tuning.
GPT-2 uses only the decoder portion of the Transformer (with masked self-attention), removing the encoder and cross-attention entirely:
| Model | Layers | d_model | Heads | Parameters |
|---|---|---|---|---|
| GPT-2 Small | 12 | 768 | 12 | 117M |
| GPT-2 Medium | 24 | 1024 | 16 | 345M |
| GPT-2 Large | 36 | 1280 | 20 | 774M |
| GPT-2 XL | 48 | 1600 | 25 | 1.5B |
GPT-2 uses byte-level BPE with a vocabulary of 50,257 tokens. Unlike WordPiece (BERT), BPE operates on raw bytes, meaning it can encode any string — no unknown tokens.
GPT-2 is trained with a simple next-token prediction objective — predicting each token given all previous tokens:
The causal mask in self-attention ensures that position t can only attend to positions ≤ t:
Unlike BERT's 15% token prediction, GPT-2 predicts every token in the sequence (just shifted by 1). This means GPT-2 gets a training signal from 100% of tokens vs BERT's 15%.
At inference time, GPT-2 generates text one token at a time. At each step, it feeds all previous tokens through the model and samples the next token from the output distribution:
T → 0 is greedy; T → ∞ is uniform random.
GPT-2 made several key changes to the original Transformer decoder:
GPT-2 was one of the first demonstrations that bigger models get consistently better. Training data: WebText, ~40GB of web text curated from Reddit links with 3+ upvotes.
GPT-2's four model sizes showed a smooth, predictable improvement with scale — laying the groundwork for GPT-3 (175B), GPT-4, and the "scaling laws" era of AI research.
GPT-2's remarkable finding: without any fine-tuning or labeled data, the model can perform tasks by conditioning on natural language descriptions:
During autoregressive generation, the model generates one token at a time. Without caching, it recomputes K,V for all previous tokens at every step — waste of O(n²) compute. The KV cache stores computed K,V matrices from previous steps:
For a 70B model generating 32K tokens, the KV cache alone can exceed 40GB. GQA (Qwen, LLaMA) reduces this by sharing KV heads. MLA (DeepSeek) compresses it by 93%. Without these tricks, large-batch inference on consumer GPUs would be impossible.
Understanding parameter counts helps build intuition. Here's the exact breakdown for GPT-2 Small:
| Component | Shape | Parameters | % |
|---|---|---|---|
| Token Embedding | 50257 × 768 | 38.6M | 33% |
| Position Embedding | 1024 × 768 | 0.8M | 0.7% |
| Per Layer (×12): | |||
| Attention WQ,WK,WV | 3 × (768×768) | 1.77M | |
| Attention WO | 768 × 768 | 0.59M | |
| FFN W₁ (expand) | 768 × 3072 | 2.36M | |
| FFN W₂ (project) | 3072 × 768 | 2.36M | |
| 2× LayerNorm (γ,β) | 2 × (768+768) | 0.003M | |
| Layer subtotal | 7.09M | ||
| 12 Layers | 85.1M | 72.7% | |
| Final LayerNorm | 768+768 | 0.002M | |
| Output (tied w/ emb) | — | 0 | 0% |
| TOTAL | ~117M | 100% | |
The FFN layers contain 2× more parameters than attention layers! This is where most "knowledge" is stored. The embedding matrix is also huge — it's basically a 50K-word dictionary where each word has a 768-dimensional definition. Weight tying (sharing embeddings with the output layer) saves 38.6M parameters.
If you're used to Word2Vec or GloVe from the LSTM era, GPT-2's embeddings work similarly — but they're trained end-to-end with the model. Each of 50,257 tokens gets a 768-dimensional vector:
Unlike Word2Vec (fixed, trained separately), GPT-2's embeddings are trained jointly with all layers. This means the embeddings learn what's most useful for next-token prediction, not just semantic similarity. They also encode syntactic role, frequency, and subword structure — all in 768 dimensions.
Let's trace one complete training step through GPT-2, from raw text all the way through backpropagation and weight updates. We'll use a tiny model (, 2 heads, 1 layer) so we can show actual numbers at every step.
Input sentence: "The cat sat on"
Goal: Predict the next token at each position:
"The" → "cat", "The cat" → "sat", "The cat sat" → "on"
The BPE tokenizer splits the input string into subword tokens and maps each to an integer ID from the vocabulary (size 50,257):
[464, 3797, 3332, 319] | Target IDs (shifted): [3797, 3332, 319]
During training, the model sees all input tokens simultaneously (not one at a time like inference). The target is the same sequence shifted left by 1 position. The causal mask prevents cheating.
Each token ID is used to look up a row from two embedding tables, then they're summed:
"The"" cat"" sat"" on"pos 0pos 1pos 2pos 3First, Pre-LayerNorm is applied. Then we compute Q, K, V projections, apply the causal mask, and compute attention output. Using 2 heads with :
Linear projections split into 2 heads (each head gets dimensions):
After attention, each token position goes through a 2-layer FFN (with GELU activation) independently:
The 4× expansion (d→4d→d) gives the FFN layers more parameters to store knowledge. Research shows FFN layers act as key-value memories: W₁ rows are "keys" that match input patterns, W₂ columns are "values" that produce associated outputs. More neurons = more facts stored.
After the final layer, a final LayerNorm and linear projection maps each position to vocabulary-sized logits:
GPT-2 shares weights between the token embedding matrix and the output projection. So (50257 × d). This saves millions of parameters.
At each position, we compute the cross-entropy between the predicted distribution and the true next token:
A loss of 3.01 means the model is assigning ~5% probability to the correct token on average. After training, we want this to drop below 1.0 (>37% on the correct token).
Perplexity is the exponential of the loss. It represents how many equally-likely tokens the model is choosing between. A perplexity of 20.3 means the model is "as confused as if it were randomly picking from 20 tokens" at each step.
The loss gradient flows backwards through every operation using the chain rule. The gradient of cross-entropy loss w.r.t. the logits has a beautifully simple form:
This is just the predicted probability minus the one-hot target — the gradient is large when the model is wrong and small when it's right.
The gradient through softmax attention is:
Without residual connections, gradients in a 48-layer model would vanish or explode. The skip connections create a "gradient highway" — gradients can flow directly from the loss to early layers without being multiplied by dozens of weight matrices.
GPT-2 uses the Adam optimizer with weight decay. For each parameter θ:
Steps 1-8 repeat for every batch of training data. GPT-2 was trained for ~800,000 steps × batch_size 512 = ~400 billion tokens. After enough iterations, the model's loss drops and it begins generating coherent, contextual text.
| Training Stage | Loss | Model Behavior |
|---|---|---|
| Step 0 (random) | ~10.8 (≈ log 50257) | Random noise output |
| Step 1K | ~6.0 | Learns common words ("the", "a", "is") |
| Step 10K | ~4.0 | Basic grammar emerges |
| Step 100K | ~3.0 | Coherent sentences, some facts |
| Step 800K (done) | ~2.85 | Fluent text, zero-shot task abilities |
GPT-2 established that scale + simple objectives = emergent capabilities. Its decoder-only, autoregressive design became the blueprint for all subsequent LLMs (GPT-3, GPT-4, Claude, Gemini, LLaMA, etc.).
Radford, A., Wu, J., Child, R., et al. "Language Models are Unsupervised Multitask Learners." OpenAI Technical Report, 2019. PDF
A 7B-parameter model in FP16 needs 14GB of VRAM — more than most consumer GPUs. Quantization reduces precision to make models fit:
| Method | Bits | 7B Model Size | Quality Loss | Speed |
|---|---|---|---|---|
| FP16 (baseline) | 16 | 14 GB | — | 1× |
| INT8 | 8 | 7 GB | ~0.1% | 1.2× |
| INT4 (GPTQ) | 4 | 3.5 GB | ~1-2% | 1.5× |
| INT4 (AWQ) | 4 | 3.5 GB | ~0.5% | 1.5× |
| GGUF Q4_K_M | 4.5 avg | 4.1 GB | ~0.8% | CPU friendly |
INT8 is almost lossless for any model. INT4 works great for 13B+ models but can hurt quality for smaller ones. A Q4-quantized 70B model often beats a FP16 7B model — because model size matters more than precision.
Autoregressive generation is slow because each token requires a full forward pass. Speculative decoding uses a small, fast "draft" model to propose multiple tokens, then the large model verifies them in a single forward pass:
Speculative decoding is mathematically equivalent to standard decoding — accepted tokens have exactly the same distribution. The draft model only proposes candidates; the target model makes all final decisions. If the draft model is bad, you just get fewer accepted tokens (slower, not worse).
LLMs have a knowledge cutoff and can't access your private data. RAG solves this by retrieving relevant documents and feeding them as context:
| Approach | Use When | Pros | Cons |
|---|---|---|---|
| RAG | Need fresh/private data access | No retraining, always up-to-date | Retrieval quality matters |
| Fine-tuning | Need new behavior/format | Reliable, fast inference | Data goes stale |
| Long Context | Entire doc fits in context | Simplest approach | Expensive, "lost in the middle" |
LLMs are next-token predictors, not knowledge databases. They can generate fluent but factually incorrect text:
The most practical skill for working with LLMs. No fine-tuning needed — just craft better prompts:
| Technique | How | When | Example |
|---|---|---|---|
| Zero-shot | Just ask | Simple tasks | "Translate to French: Hello" |
| Few-shot | Give 2-5 examples first | Need specific format | "positive: good → 1\nnegative: bad → 0\n??? awful →" |
| Chain-of-Thought | Add "Let's think step by step" | Math, reasoning | Accuracy jumps 30-50% on GSM8K |
| System Prompt | Set role, constraints | Consistent behavior | "You are a JSON API. Only output valid JSON." |
| ReAct | Thought → Action → Observation loop | Tool use, agents | "I need to search for... [calls API]... Based on..." |
# Few-shot classification — the model learns the pattern Review: "The food was amazing!" → Sentiment: positive Review: "Worst service ever." → Sentiment: negative Review: "It was okay, nothing special." → Sentiment: neutral Review: "Absolutely loved the ambiance!" → Sentiment: ??? # Model outputs: positive (no training needed!)
During pre-training, the model saw millions of patterns like "Q: ... A: ...". Few-shot examples activate these patterns. The model isn't "learning" — it's pattern-matching against its training distribution. This is why larger models are better at in-context learning: they've seen more diverse patterns.
Serving LLMs to millions of users requires specialized infrastructure beyond simple model.generate():
| Innovation | Problem Solved | Impact | Used By |
|---|---|---|---|
| PagedAttention | KV cache wastes memory (fragmentation) | 2-4× more concurrent users | vLLM |
| Continuous Batching | Static batching wastes GPU on finished sequences | 10-20× throughput vs naive | vLLM, TGI |
| Tensor Parallelism | Model too large for 1 GPU | Split layers across GPUs | All serving frameworks |
| Prefix Caching | Same system prompt repeated | Skip redundant computation | SGLang |
class GPT2Block(nn.Module): """Pre-LayerNorm decoder block (GPT-2 style)""" def __init__(self, d_model=768, n_heads=12, d_ff=3072): super().__init__() self.ln1 = nn.LayerNorm(d_model) self.attn = MultiHeadAttention(d_model, n_heads) self.ln2 = nn.LayerNorm(d_model) self.ffn = nn.Sequential( nn.Linear(d_model, d_ff), nn.GELU(), # GPT-2 uses GELU, not ReLU nn.Linear(d_ff, d_model), ) def forward(self, x): # Pre-norm + causal attention + residual x = x + self.attn(self.ln1(x), causal=True) # Pre-norm + FFN + residual x = x + self.ffn(self.ln2(x)) return x
class GPT2(nn.Module): def __init__(self, vocab=50257, d=768, layers=12, heads=12, ctx=1024): super().__init__() self.tok_emb = nn.Embedding(vocab, d) self.pos_emb = nn.Embedding(ctx, d) self.blocks = nn.Sequential(*[GPT2Block(d, heads) for _ in range(layers)]) self.ln_f = nn.LayerNorm(d) # Weight tying: output projection shares weights with tok_emb def forward(self, idx): B, T = idx.shape pos = torch.arange(T, device=idx.device) x = self.tok_emb(idx) + self.pos_emb(pos) # (B, T, d) x = self.ln_f(self.blocks(x)) # Tied weights: logits = x @ tok_emb.weight.T logits = x @ self.tok_emb.weight.T # (B, T, vocab) return logits model = GPT2() print(f"Parameters: {sum(p.numel() for p in model.parameters()):,}") # Parameters: ~124,439,808 (124M)
@torch.no_grad() def generate(model, idx, max_new_tokens=50, temperature=0.8): """Autoregressive generation with temperature sampling""" for _ in range(max_new_tokens): # Crop to context window (1024) idx_cond = idx[:, -1024:] logits = model(idx_cond)[:, -1, :] # last token logits logits = logits / temperature probs = F.softmax(logits, dim=-1) next_tok = torch.multinomial(probs, num_samples=1) idx = torch.cat([idx, next_tok], dim=1) return idx # Generate from "The cat" prompt = torch.tensor([[464, 3797]]) # BPE IDs for "The cat" output = generate(model, prompt)