Chapter 04 — Decoder Models

GPT-2: Language Models are Unsupervised Multitask Learners

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.

Guided Track: Prompt to Production

Read this chapter in three passes: start with objective and masking, then move to generation controls, then finish with serving and reliability patterns.

Pass 1: Model Core

  • Decoder-only architecture
  • Causal masking and token-by-token prediction
  • BPE tokenization and context windows

Pass 2: Generation Control

  • Greedy, top-k, top-p, and temperature
  • KV cache for fast inference
  • Prompt format as an interface layer

Pass 3: Practical Systems

  • RAG for factual grounding
  • Hallucination patterns and mitigations
  • Serving, batching, and latency trade-offs

Autoregressive Core Objective

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.

The GPT Philosophy

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.

🔑 Key Difference from BERT

BERT = Encoder-only, bidirectional, requires task-specific fine-tuning.
GPT-2 = Decoder-only, unidirectional (left-to-right), performs tasks via prompting without fine-tuning.

Decoder-Only Architecture

GPT-2 uses only the decoder portion of the Transformer (with masked self-attention), removing the encoder and cross-attention entirely:

ModelLayersd_modelHeadsParameters
GPT-2 Small1276812117M
GPT-2 Medium24102416345M
GPT-2 Large36128020774M
GPT-2 XL481600251.5B
Linear + Softmax → P(next token)
↑
× N layers
Layer Norm
↑
Feed-Forward (4 × d_model)
↑ + residual
Layer Norm
↑
Masked Multi-Head Self-Attention
↑ + residual
Token Emb
+
Position Emb
Input: "The quick brown fox"
Fig 1. GPT-2 architecture. Note: Layer Norm is moved to the input of each sub-layer (pre-norm), unlike the original Transformer (post-norm). This critical change improves training stability.

Byte-Pair Encoding (BPE) Tokenization

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.

How BPE Works

  1. Start with a vocabulary of all individual bytes (256 tokens)
  2. Find the most frequent pair of adjacent tokens in the corpus
  3. Merge them into a new token and add to vocabulary
  4. Repeat until vocabulary size is reached
Example: "transformer" → BPE tokens
Step 1 (bytes):
t
r
a
n
s
f
o
r
m
e
r
↓ merge frequent pairs
Final:
trans
former

Causal Language Modeling

GPT-2 is trained with a simple next-token prediction objective — predicting each token given all previous tokens:

Cross-entropy loss for autoregressive language modeling

The causal mask in self-attention ensures that position t can only attend to positions ≤ t:

💡 Training Efficiency

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%.

Autoregressive Generation

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:

Decoding Strategies

Concrete Example: Same Logits, Different Strategies

Raw logits: {"the": 5.2, "a": 3.8, "my": 3.1, "his": 1.4, "some": 0.9, ...49K more}

① Greedy: always "the" → "the the the the..." (boring!)

② T=0.5 (sharp): softmax(logits/0.5)
  "the"=0.71, "a"=0.18, "my"=0.08, "his"=0.02, ...
  → almost always picks "the" or "a"

③ T=2.0 (flat): softmax(logits/2.0)
  "the"=0.22, "a"=0.16, "my"=0.14, "his"=0.10, ...
  → creative but can be incoherent

④ Top-k=3: keep only top 3, renormalize
  "the"=0.54, "a"=0.29, "my"=0.17 (rest zeroed)

⑤ Top-p=0.9: keep smallest set summing to ≥0.9
  "the"(0.48) + "a"(0.25) + "my"(0.17) = 0.90 ← stop here
  3 tokens kept (dynamic k!)

Architectural Modifications from Original Transformer

GPT-2 made several key changes to the original Transformer decoder:

  1. Pre-Norm: Layer normalization is applied before each sub-layer (instead of after). This improves gradient flow and training stability.
  2. Learned positional embeddings instead of sinusoidal (up to 1024 positions)
  3. Scaled initialization: Residual layer weights initialized by where N is the number of layers
  4. Larger vocabulary: 50,257 BPE tokens vs Transformer's 37K
  5. Context length: 1024 tokens (vs 512 for BERT)

Scaling Laws

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.

📊 The Scaling Hypothesis

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.

Zero-Shot Learning

GPT-2's remarkable finding: without any fine-tuning or labeled data, the model can perform tasks by conditioning on natural language descriptions:

TRANSLATION (Zero-Shot)
Translate English to French:
The cat is black =
Le chat est noir
SUMMARIZATION (Zero-Shot)
Article: [long text...]
TL;DR:
A concise summary...
Q&A (Zero-Shot)
Q: What is the capital of France?
A:
Paris

The KV Cache: Why Inference is Memory-Bound

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:

Step 1: "The" → compute K₁,V₁, store in cache
Step 2: " cat" → compute K₂,V₂, append. Q₂ attends to [K₁,K₂]
Step 3: " sat" → compute K₃,V₃, append. Q₃ attends to [K₁,K₂,K₃]

KV cache size per token per layer:
= 2 × dmodel = 2 × 768 = 1,536 values (FP16 = 3,072 bytes)

GPT-2 Small, 1024 tokens:
= 12 layers × 1024 tokens × 3,072 bytes = 37.7 MB

GPT-2 XL (d=1600, 48 layers), 1024 tokens:
= 48 × 1024 × 2 × 1600 × 2 bytes = 314 MB
⚡ This is why GQA and MLA exist

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.

Where Do 117M Parameters Come From?

Understanding parameter counts helps build intuition. Here's the exact breakdown for GPT-2 Small:

ComponentShapeParameters%
Token Embedding50257 × 76838.6M33%
Position Embedding1024 × 7680.8M0.7%
Per Layer (×12):
  Attention WQ,WK,WV3 × (768×768)1.77M
  Attention WO768 × 7680.59M
  FFN W₁ (expand)768 × 30722.36M
  FFN W₂ (project)3072 × 7682.36M
  2× LayerNorm (γ,β)2 × (768+768)0.003M
  Layer subtotal7.09M
12 Layers85.1M72.7%
Final LayerNorm768+7680.002M
Output (tied w/ emb)—00%
TOTAL~117M100%
💡 Key Insight

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.

Embedding Space: How Words Become Vectors

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:

Token "cat" (ID: 9246):
→ look up row 9246 in the embedding table
→ get vector: [0.12, -0.87, 0.45, ..., 0.33] (768 dims)

What do these dimensions encode?
Dim 42: animate?   "cat"=0.92 "rock"=-0.71
Dim 156: size?     "cat"=0.15 "elephant"=0.89
Dim 387: sentiment? "love"=0.81 "hate"=-0.76

Vector arithmetic still works:
king − man + woman ≈ queen
Paris − France + Germany ≈ Berlin

Cosine similarity → semantic closeness:
cos("cat", "kitten") = 0.89 (very close)
cos("cat", "truck")  = 0.12 (far apart)
💡 From Word2Vec to LLM Embeddings

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.

🔥 Full Training Pipeline

Full Training Pipeline: End-to-End Example

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.

📝 Our Training Example

Input sentence: "The cat sat on"
Goal: Predict the next token at each position:
"The" → "cat", "The cat" → "sat", "The cat sat" → "on"

Full Architecture: Data Flow Through GPT-2

① Input Text
"The cat sat on"
↓ BPE Tokenizer
② Token IDs: [464, 3797, 3332, 319]
↓ lookup
Token Emb
50257×768
+
Pos Emb
1024×768
h⁰ ∈ ℝ4×768
× 12 Decoder Layers
③ Pre-LayerNorm
↓
③ Masked Multi-Head Self-Attention
12 heads × dk=64, causal mask
↓ + residual skip
④ Pre-LayerNorm
↓
④ FFN: 768 → 3072 → 768
GELU activation
↓ + residual skip
hL ∈ ℝ4×768
⑤ Final LayerNorm
↓ × WembedT (tied weights!)
⑤ Output Logits ∈ ℝ4×50257
↓ softmax
⑥ Cross-Entropy Loss
↓ ∂L/∂θ
⑦ Backprop
⑧ Adam Update
Complete GPT-2 architecture. Circled numbers ①-⑧ correspond to pipeline steps below. Data shapes shown for GPT-2 Small (768-dim, 12 layers, 12 heads).

Step 1: Tokenization (Text → Token IDs)

The BPE tokenizer splits the input string into subword tokens and maps each to an integer ID from the vocabulary (size 50,257):

"The cat sat on"
↓ BPE Tokenizer
"The" → 464
" cat" → 3797
" sat" → 3332
" on" → 319
Input IDs: [464, 3797, 3332, 319]  |  Target IDs (shifted): [3797, 3332, 319]
⚠️ Teacher Forcing

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.

Step 2: Embedding Lookup (IDs → Vectors)

Each token ID is used to look up a row from two embedding tables, then they're summed:

Token
Token Emb (lookup row from 50257 × d table)
"The"
E_tok[464] = [0.21, −0.55, 0.78, 0.12]
" cat"
E_tok[3797] = [0.65, 0.33, −0.41, 0.88]
" sat"
E_tok[3332] = [−0.12, 0.91, 0.45, −0.67]
" on"
E_tok[319] = [0.44, −0.23, 0.56, 0.31]
+ Position Embeddings (learned, from 1024 × d table)
pos 0
E_pos[0] = [0.10, 0.05, −0.08, 0.03]
pos 1
E_pos[1] = [−0.05, 0.12, 0.06, −0.09]
pos 2
E_pos[2] = [0.08, −0.03, 0.11, 0.07]
pos 3
E_pos[3] = [−0.02, 0.08, −0.04, 0.15]
= h⁰ (Input to first layer) — shape: 4 × d
h⁰ = [[0.31, −0.50, 0.70, 0.15],   [0.60, 0.45, −0.35, 0.79],   [−0.04, 0.88, 0.56, −0.60],   [0.42, −0.15, 0.52, 0.46]]

Step 3: Masked Multi-Head Self-Attention

First, Pre-LayerNorm is applied. Then we compute Q, K, V projections, apply the causal mask, and compute attention output. Using 2 heads with :

3a. LayerNorm

3b. Q, K, V Projections

Linear projections split into 2 heads (each head gets dimensions):

Head 1 (dims 0-1)
Q₁: [0.42, 0.18] [0.71, −0.33] [−0.15, 0.82] [0.55, 0.27]
K₁: [0.35, −0.22] [0.58, 0.44] [0.12, 0.67] [0.41, 0.09]
V₁: [0.28, 0.65] [−0.13, 0.51] [0.72, −0.08] [0.39, 0.44]
Head 2 (dims 2-3)
Q₂: [0.61, −0.45] [0.23, 0.78] [0.44, 0.12] [−0.31, 0.66]
K₂: [0.52, 0.31] [−0.18, 0.63] [0.47, −0.25] [0.33, 0.58]
V₂: [0.41, −0.22] [0.55, 0.33] [−0.27, 0.61] [0.48, 0.15]

3c. Attention Scores + Causal Mask (Head 1)

Q₁K₁ᵀ / √2
[0.10, 0.21, 0.12, 0.13]
[0.22, 0.19, 0.04, 0.27]
[−0.17, 0.17, 0.38, 0.04]
[0.10, 0.31, 0.19, 0.18]
+
Causal Mask M
[0, −∞, −∞, −∞]
[0, 0, −∞, −∞]
[0, 0, 0, −∞]
[0, 0, 0, 0]

3d. Softmax → Attention Weights

"The":   [1.00, 0.00, 0.00, 0.00] ← only sees itself
" cat":  [0.49, 0.51, 0.00, 0.00] ← sees "The", " cat"
" sat":  [0.22, 0.34, 0.44, 0.00] ← sees first 3
" on":   [0.22, 0.29, 0.25, 0.24] ← sees all 4

3e. Weighted Value Sum + Output Projection

Step 4: Feed-Forward Network

After attention, each token position goes through a 2-layer FFN (with GELU activation) independently:

h_attn (d=4 per token)
↓ LayerNorm
W₁: d → 4d = 16  (expand)
↓ GELU activation
W₂: 4d → d = 4  (project back)
↓ + residual
h¹ (output of layer 1)
⚡ Why expand to 4×?

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.

Step 5: Output Logits & Probabilities

After the final layer, a final LayerNorm and linear projection maps each position to vocabulary-sized logits:

💡 Weight Tying

GPT-2 shares weights between the token embedding matrix and the output projection. So (50257 × d). This saves millions of parameters.

For position 0 ("The"): predict next token
logits[0] = h_final[0] × W_embed^T → [... 50,257 values ...]

Top 5 after softmax:
  P("cat") = 0.08  ← want this to be HIGH
  P("dog") = 0.05
  P("the") = 0.04
  P(",")   = 0.03
  P("man") = 0.03
  ... (50,252 other tokens share remaining ~0.77)

Step 6: Cross-Entropy Loss Calculation

At each position, we compute the cross-entropy between the predicted distribution and the true next token:

Position 0
"The" → ?
Target: "cat"
P(cat) = 0.08
−log(0.08) = 2.53
Position 1
"cat" → ?
Target: "sat"
P(sat) = 0.03
−log(0.03) = 3.51
Position 2
"sat" → ?
Target: "on"
P(on) = 0.05
−log(0.05) = 3.00
Total Loss = (2.53 + 3.51 + 3.00) / 3 = 3.01

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: Interpreting the Loss

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.

Random (untrained): PPL = 50,257 (vocab size)
Step 1K:   Loss=6.0 → PPL = 403
Step 10K: Loss=4.0 → PPL = 55
Step 100K: Loss=3.0 → PPL = 20
Final:    Loss=2.85 → PPL = 17.3 ← GPT-2 on WebText

Step 7: Backpropagation

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.

Gradient Flow Path (reverse order)

∂L/∂logits = softmax(logits) − one_hot(target)
↓ chain rule through W_embed^T
∂L/∂h_final → through LayerNorm
↓ split at residual: ∂L/∂FFN + ∂L/∂skip
∂L/∂W₂, ∂L/∂W₁ → through FFN (GELU derivative)
↓ split at residual: ∂L/∂MHA + ∂L/∂skip
∂L/∂W^Q, ∂L/∂W^K, ∂L/∂W^V, ∂L/∂W^O
↓ through attention softmax & mask
∂L/∂E_token, ∂L/∂E_position → embedding gradients

Key Backprop Through Attention

The gradient through softmax attention is:

💡 Residual Connections Save Training

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.

Step 8: Weight Update (Adam Optimizer)

GPT-2 uses the Adam optimizer with weight decay. For each parameter θ:

Concrete example: updating one weight in W^Q
g = ∂L/∂w = 0.0234  (gradient)
m = 0.9 × 0.0 + 0.1 × 0.0234 = 0.00234
v = 0.999 × 0.0 + 0.001 × 0.0234² = 5.48e-7
m̂ = 0.00234 / (1 − 0.9¹) = 0.0234
v̂ = 5.48e-7 / (1 − 0.999¹) = 5.48e-4

w_old = 0.4521
Δw = −0.0001 × (0.0234 / (√5.48e-4 + 1e-8) + 0.01 × 0.4521)
Δw = −0.0001 × (0.999 + 0.00452) = −0.0001004
w_new = 0.4521 − 0.0001 = 0.4520
This update happens for all ~117M parameters simultaneously!
🔄 One training loop complete!

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 Progress Summary

Training StageLossModel Behavior
Step 0 (random)~10.8 (≈ log 50257)Random noise output
Step 1K~6.0Learns common words ("the", "a", "is")
Step 10K~4.0Basic grammar emerges
Step 100K~3.0Coherent sentences, some facts
Step 800K (done)~2.85Fluent text, zero-shot task abilities

Impact & Legacy

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.).

📄 Citation

Radford, A., Wu, J., Child, R., et al. "Language Models are Unsupervised Multitask Learners." OpenAI Technical Report, 2019. PDF

Quantization: Running LLMs on Consumer Hardware

A 7B-parameter model in FP16 needs 14GB of VRAM — more than most consumer GPUs. Quantization reduces precision to make models fit:

MethodBits7B Model SizeQuality LossSpeed
FP16 (baseline)1614 GB—1×
INT887 GB~0.1%1.2×
INT4 (GPTQ)43.5 GB~1-2%1.5×
INT4 (AWQ)43.5 GB~0.5%1.5×
GGUF Q4_K_M4.5 avg4.1 GB~0.8%CPU friendly
How INT4 quantization works:
FP16 weight: 0.0347 → map to nearest INT4 value
INT4 range: -8 to +7 (16 levels)
scale = max(|weights|) / 7
quantized = round(weight / scale) → store as 4-bit int
dequantized = quantized × scale ≈ 0.0343 (close!)

GPTQ vs AWQ:
GPTQ: quantize all weights equally
AWQ: protect "salient" weights (1% that matter most)
→ AWQ gets better quality at same size
⚡ Rule of Thumb

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.

Speculative Decoding: 2-3× Faster Inference

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:

Standard: 5 tokens = 5 forward passes
[The] → forward → [cat] → forward → [sat] → ...
Total: 5 × 50ms = 250ms

Speculative: 5 tokens ≈ 2 forward passes
Step 1: Draft model (1B): proposes "cat sat on the"
Step 2: Target model (70B): verifies all 4 at once
→ accepts "cat sat on" ✓, rejects "the" → samples "a" instead
→ 3 tokens accepted in 1 large forward pass!

Total: 1×5ms(draft) + 2×50ms(verify) = 105ms (2.4× faster)

Key insight: Verification is parallel — checking 5 tokens
costs the same as generating 1 (it's just a batch dimension).
💡 No Quality Loss!

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).

RAG: Retrieval-Augmented Generation

LLMs have a knowledge cutoff and can't access your private data. RAG solves this by retrieving relevant documents and feeding them as context:

User Query
"What's our refund policy?"
→
Embed + Search
Vector DB (FAISS/Pinecone)
→
Top-K Docs
3 most relevant chunks
→
LLM + Context
Answer grounded in docs
ApproachUse WhenProsCons
RAGNeed fresh/private data accessNo retraining, always up-to-dateRetrieval quality matters
Fine-tuningNeed new behavior/formatReliable, fast inferenceData goes stale
Long ContextEntire doc fits in contextSimplest approachExpensive, "lost in the middle"

Hallucination: Why LLMs Make Things Up

LLMs are next-token predictors, not knowledge databases. They can generate fluent but factually incorrect text:

Why it happens:
1. Statistical pattern matching — model learned P("Paris is the capital of") → "France" is high, but P("The population of X is") → any plausible number
2. Training data gaps — model fills unknowns with plausible-sounding completions
3. Sycophancy — model agrees with user even when incorrect
4. No "I don't know" — pre-training has no examples of refusing to answer

Mitigation strategies:
✓ RAG — ground answers in retrieved documents
✓ Search-grounded — verify facts with web search
✓ Confidence scoring — detect low-confidence outputs
✓ Chain-of-Verification — model self-checks its claims
✓ RLHF/DPO — train model to say "I don't know"

Prompt Engineering & In-Context Learning

The most practical skill for working with LLMs. No fine-tuning needed — just craft better prompts:

TechniqueHowWhenExample
Zero-shotJust askSimple tasks"Translate to French: Hello"
Few-shotGive 2-5 examples firstNeed specific format"positive: good → 1\nnegative: bad → 0\n??? awful →"
Chain-of-ThoughtAdd "Let's think step by step"Math, reasoningAccuracy jumps 30-50% on GSM8K
System PromptSet role, constraintsConsistent behavior"You are a JSON API. Only output valid JSON."
ReActThought → Action → Observation loopTool use, agents"I need to search for... [calls API]... Based on..."
Few-shot prompt example
# 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!)
⚡ Why In-Context Learning Works

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.

Inference Serving: Production LLM Deployment

Serving LLMs to millions of users requires specialized infrastructure beyond simple model.generate():

InnovationProblem SolvedImpactUsed By
PagedAttentionKV cache wastes memory (fragmentation)2-4× more concurrent usersvLLM
Continuous BatchingStatic batching wastes GPU on finished sequences10-20× throughput vs naivevLLM, TGI
Tensor ParallelismModel too large for 1 GPUSplit layers across GPUsAll serving frameworks
Prefix CachingSame system prompt repeatedSkip redundant computationSGLang
PagedAttention (vLLM's key innovation):
Traditional: pre-allocate max_len KV cache per request
→ 2048 tokens × 768 dims = wasted 90% if output is 200 tokens

PagedAttention: allocate KV cache in 16-token "pages"
→ Only allocate pages as needed, like OS virtual memory
→ Near-zero waste, 2-4× more concurrent requests

Continuous Batching:
Static: wait until ALL sequences finish → GPU idles
Continuous: when seq finishes, immediately add new request
→ GPU stays 100% utilized
💻 PyTorch Code

Code: GPT-2 from Scratch

GPT-2 Decoder Block

Python
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

Full GPT-2 Model

Python
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)

Text Generation

Python
@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)