GPT-2 from Scratch
Assembling every piece into a working language model.
The previous article assembled the transformer block: multi-head attention and a feed-forward network, each wrapped in a Pre-LN residual connection. Stacking identical blocks produces a powerful sequence processor. What it is not yet is a language model. Two things are still missing: a way to convert a token ID sequence into the tensors the blocks expect, and a way to convert the blocks' output back into a probability distribution over the vocabulary. GPT-2 adds both, and the result is a complete, trainable language model.
The Language Modeling Objective
A language model assigns a probability to a sequence of tokens. The autoregressive factorization decomposes this into a product of conditional probabilities:
At each position , the model receives the preceding context and produces a probability distribution over the -token vocabulary. Training maximizes the log-likelihood of the training data, which is equivalent to minimizing the average cross-entropy:
This is the same cross-entropy loss introduced in the Loss Functions article, applied at every position in the sequence. Because the transformer processes all positions in parallel, a single forward pass of length produces independent next-token predictions simultaneously. Causal masking in each attention layer ensures position cannot see tokens during this computation.
Architecture Overview
The model has three stages.
Input stage. A sequence of token IDs is converted to -dimensional vectors by combining two learned embedding tables.
Body. The sequence flows through identical transformer blocks in series. The shape is preserved at every block boundary.
Output stage. A final layer normalization is applied to the output of the last block, then a linear projection maps each position from to logits. Softmax produces the next-token probability distribution.
Input Embeddings
Two learned tables combine to form the input to the first block:
is the token embedding table from the Tokenization and Embeddings article: each row is a -dimensional learned vector for one vocabulary entry.
is a learned positional embedding table. The Positional Encoding article presented sinusoidal encodings computed from a fixed formula. GPT-2 takes a simpler approach: it allocates one trainable row for each of the positions it supports, and lets gradient descent find the best representation for each position. The two tables are added element-wise before the first block, so every position enters with both its token identity and its location encoded.
For GPT-2 small (, ):
| Table | Shape | Parameters |
|---|---|---|
| Token embedding | ||
| Positional embedding |
Weight Tying
The output stage needs a matrix of shape to project hidden states to logits. This is exactly the transpose of the token embedding table .
GPT-2 reuses the same matrix for both purposes:
where is the normalized hidden state at some position. The model predicts the next token by measuring how similar the current hidden state is to each row of the embedding table. This weight tying removes parameters from the count and tends to improve performance: the embedding space used to represent input tokens is forced to be consistent with the space used to score output tokens.
The LM Head
The complete output computation for a position is:
where is the output of the last transformer block. GPT-2 introduced a final layer normalization after the last block, applied before the output projection. Applying softmax to the logits produces the probability distribution over the next token.
During training, logits at position are compared against the ground-truth token with cross-entropy. The sequence is shifted by one: the input to the model is and the targets are , so every position has a label.
Autoregressive Generation
Training uses teacher forcing: the correct tokens are fed at every step regardless of what the model predicts. At inference time, the model instead conditions each new token on its own previous outputs.
Given a prompt :
- Run a forward pass. The logits at position encode the distribution for .
- Sample from this distribution.
- Append to the sequence.
- Repeat from step 1 with the extended context.
Generation terminates when the model produces a special end-of-sequence token or a maximum length is reached.
Temperature. Before sampling, the logits are divided by a temperature :
leaves the model's learned distribution unchanged. concentrates probability on the highest-scoring tokens, producing more predictable output. spreads probability more evenly, producing more varied output.
Top- sampling. Before softmax, all logits below the -th highest are set to . Only the most likely candidates survive. GPT-2's original paper used .
Top- (nucleus) sampling. Instead of a fixed , retain the smallest set of tokens whose cumulative probability exceeds , and sample from that set. At the model draws from the top 90% of probability mass, with the number of candidates adapting automatically to the model's confidence at each step.
Complete Parameter Count
For GPT-2 small (, , , , ):
| Component | Parameters |
|---|---|
| Token embedding | |
| Positional embedding | |
| 12 transformer blocks ( each) | |
| Final LayerNorm () | |
| LM head (tied to ) | (shared) |
| Total |
The token embedding table accounts for 31% of the total at this scale. As models grow wider and deeper, the transformer blocks dominate: each block holds parameters, which grows quadratically with while the embedding tables grow only linearly.
In Code
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
# ═══════════════════════════════════════════════════════════════════════════════
# Building blocks from the previous articles
# ═══════════════════════════════════════════════════════════════════════════════
class MultiHeadAttention(nn.Module):
def __init__(self, d_model: int, num_heads: int):
super().__init__()
assert d_model % num_heads == 0
self.H, self.dk = num_heads, d_model // num_heads
self.W_Q = nn.Linear(d_model, d_model, bias=False)
self.W_K = nn.Linear(d_model, d_model, bias=False)
self.W_V = nn.Linear(d_model, d_model, bias=False)
self.W_O = nn.Linear(d_model, d_model, bias=False)
def forward(self, x: torch.Tensor, causal: bool = True) -> torch.Tensor:
B, T, D = x.shape
split = lambda t: t.view(B, T, self.H, self.dk).transpose(1, 2)
Q, K, V = split(self.W_Q(x)), split(self.W_K(x)), split(self.W_V(x))
scores = Q @ K.transpose(-2, -1) / math.sqrt(self.dk)
if causal:
mask = torch.triu(torch.ones(T, T, dtype=torch.bool, device=x.device), diagonal=1)
scores = scores.masked_fill(mask, float("-inf"))
out = F.softmax(scores, dim=-1) @ V
return self.W_O(out.transpose(1, 2).contiguous().view(B, T, D))
class FFN(nn.Module):
def __init__(self, d_model: int):
super().__init__()
self.fc1 = nn.Linear(d_model, 4 * d_model)
self.fc2 = nn.Linear(4 * d_model, d_model)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.fc2(F.gelu(self.fc1(x)))
class TransformerBlock(nn.Module):
def __init__(self, d_model: int, num_heads: int):
super().__init__()
self.ln1 = nn.LayerNorm(d_model)
self.mha = MultiHeadAttention(d_model, num_heads)
self.ln2 = nn.LayerNorm(d_model)
self.ffn = FFN(d_model)
def forward(self, x: torch.Tensor, causal: bool = True) -> torch.Tensor:
x = x + self.mha(self.ln1(x), causal=causal)
x = x + self.ffn(self.ln2(x))
return x
# ═══════════════════════════════════════════════════════════════════════════════
# GPT-2: assembles every piece into a complete language model
# ═══════════════════════════════════════════════════════════════════════════════
class GPT2(nn.Module):
"""Decoder-only transformer language model (GPT-2 architecture).
Token embeddings and the LM head share the same weight matrix (weight
tying). Gradients reach wte.weight from both the embedding lookup and
the output projection — autograd accumulates them automatically.
"""
def __init__(self, vocab_size: int, d_model: int, num_heads: int,
n_layers: int, max_len: int = 1024):
super().__init__()
self.wte = nn.Embedding(vocab_size, d_model) # token embeddings
self.wpe = nn.Embedding(max_len, d_model) # positional embeddings
self.blocks = nn.ModuleList([
TransformerBlock(d_model, num_heads) for _ in range(n_layers)
])
self.ln_f = nn.LayerNorm(d_model) # final layer norm
self.lm_head = nn.Linear(d_model, vocab_size, bias=False)
self.lm_head.weight = self.wte.weight # weight tying
def forward(self, idx: torch.Tensor) -> torch.Tensor:
B, T = idx.shape
pos = torch.arange(T, device=idx.device).unsqueeze(0) # (1, T)
x = self.wte(idx) + self.wpe(pos) # (B, T, D)
for block in self.blocks:
x = block(x, causal=True)
return self.lm_head(self.ln_f(x)) # (B, T, V)
def loss(self, idx: torch.Tensor) -> torch.Tensor:
"""Next-token prediction loss over the full sequence."""
logits = self(idx[:, :-1]) # (B, T-1, V): predict tokens 1..T
targets = idx[:, 1:].contiguous() # (B, T-1): the next token at each step
B, T, V = logits.shape
return F.cross_entropy(logits.view(B * T, V), targets.view(B * T))
# ── Autoregressive generation ─────────────────────────────────────────────────
@torch.no_grad()
def generate(model: GPT2, idx: torch.Tensor, max_new_tokens: int,
temperature: float = 1.0, top_k: int = 0) -> torch.Tensor:
"""Sample tokens one by one, feeding each output back as input."""
model.eval()
for _ in range(max_new_tokens):
ctx = idx if idx.size(1) <= 1024 else idx[:, -1024:] # truncate to the context window
logits = model(ctx)[:, -1, :] / temperature # (B, V): last position only
if top_k > 0:
v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
logits[logits < v[:, [-1]]] = float("-inf")
probs = F.softmax(logits, dim=-1)
next_tok = torch.multinomial(probs, num_samples=1) # (B, 1)
idx = torch.cat([idx, next_tok], dim=1)
return idx
# ═══════════════════════════════════════════════════════════════════════════════
# Training demo: a tiny model (fast to run), same loop as for a real GPT-2
# ═══════════════════════════════════════════════════════════════════════════════
V, D, H, N = 64, 16, 2, 2 # tiny: vocab=64, d_model=16, 2 heads, 2 layers
tiny = GPT2(vocab_size=V, d_model=D, num_heads=H, n_layers=N, max_len=32)
optimizer = torch.optim.Adam(tiny.parameters(), lr=1e-2)
tiny.train()
for step in range(30):
seq = torch.randint(0, V, (1, 10)) # random 10-token sequence
optimizer.zero_grad()
loss = tiny.loss(seq) # next-token cross-entropy over all 9 positions
loss.backward() # backprop through N blocks + both embeddings
optimizer.step()
if step % 10 == 0:
print(f"step {step:2d} loss={loss.item():.4f}")
# ── Generation ────────────────────────────────────────────────────────────────
prompt = torch.tensor([[1, 5, 12]])
generated = generate(tiny, prompt, max_new_tokens=7, temperature=0.8)
print("prompt :", prompt[0].tolist())
print("generated:", generated[0].tolist()) # [1, 5, 12, <7 sampled tokens>]
# ── GPT-2 small: 12 layers, 768 dimensions, 12 heads ──────────────────────────
model = GPT2(vocab_size=50257, d_model=768, num_heads=12, n_layers=12)
x = torch.randint(0, 50257, (2, 64)) # batch=2, seq_len=64
print(model(x).shape) # torch.Size([2, 64, 50257])
total = sum(p.numel() for p in model.parameters())
print(f"{total:,}") # 124,402,944 (the tied matrix is counted once)
GPT-2 brings together every concept covered in this series: the tokenizer and BPE vocabulary, learned embeddings with weight tying, positional encodings for sequence order, causal self-attention that gives each position direct access to all preceding positions, multi-head attention for parallel specialization, residual connections and layer normalization for training stability, and the position-wise feed-forward network for per-position transformation. Stacking of these blocks and training on next-token prediction over a large text corpus is, in its essentials, how modern language models are built.