Skip to content
Transformers

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 NN 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 T×DT \times D tensors the blocks expect, and a way to convert the blocks' T×DT \times D 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:

P(t1,t2,…,tT)=∏i=1TP(ti∣t1,…,ti−1)P(t_1, t_2, \ldots, t_T) = \prod_{i=1}^{T} P(t_i \mid t_1, \ldots, t_{i-1})

At each position ii, the model receives the preceding context and produces a probability distribution over the VV-token vocabulary. Training maximizes the log-likelihood of the training data, which is equivalent to minimizing the average cross-entropy:

L=−1T∑i=1Tlog⁡P(ti∣t1,…,ti−1)\mathcal{L} = -\frac{1}{T} \sum_{i=1}^{T} \log P(t_i \mid t_1, \ldots, t_{i-1})

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 TT produces TT independent next-token predictions simultaneously. Causal masking in each attention layer ensures position ii cannot see tokens ti+1,…,tTt_{i+1}, \ldots, t_T during this computation.

Architecture Overview

idx [t₁, t₂, …, t_T]Input EmbeddingE[t] + P[pos] → x ∈ ℝ^(T×D)× NTransformer BlockMHA + FFN + LayerNorm + ResidualFinal LayerNormLM Headh · E^T (weight-tied)logits (T × V)GPT-2: causal attention throughout, weight-tied LM head

The model has three stages.

Input stage. A sequence of token IDs is converted to DD-dimensional vectors by combining two learned embedding tables.

Body. The sequence flows through NN identical transformer blocks in series. The shape T×DT \times D 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 RD\mathbb{R}^D to RV\mathbb{R}^V logits. Softmax produces the next-token probability distribution.

Input Embeddings

Two learned tables combine to form the input to the first block:

xt=E[tt]+P[t]\mathbf{x}_t = \mathbf{E}[t_t] + \mathbf{P}[t]

E∈RV×D\mathbf{E} \in \mathbb{R}^{V \times D} is the token embedding table from the Tokenization and Embeddings article: each row is a DD-dimensional learned vector for one vocabulary entry.

P∈RTmax⁡×D\mathbf{P} \in \mathbb{R}^{T_{\max} \times D} 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 Tmax⁡=1,024T_{\max} = 1{,}024 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 (D=768D = 768, V=50,257V = 50{,}257):

TableShapeParameters
Token embedding E\mathbf{E}50,257×76850{,}257 \times 768≈38.6 M\approx 38.6\text{ M}
Positional embedding P\mathbf{P}1,024×7681{,}024 \times 768≈0.8 M\approx 0.8\text{ M}

Weight Tying

The output stage needs a matrix of shape D×VD \times V to project hidden states to logits. This is exactly the transpose of the token embedding table E∈RV×D\mathbf{E} \in \mathbb{R}^{V \times D}.

GPT-2 reuses the same matrix for both purposes:

logitv=h⋅E[v]\text{logit}_v = \mathbf{h} \cdot \mathbf{E}[v]

where h∈RD\mathbf{h} \in \mathbb{R}^D 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 V×D≈38.6 MV \times D \approx 38.6\text{ M} 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:

logits=LN(h)⋅E⊤∈RV\mathbf{logits} = \text{LN}(\mathbf{h}) \cdot \mathbf{E}^\top \in \mathbb{R}^V

where h∈RD\mathbf{h} \in \mathbb{R}^D 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 ii are compared against the ground-truth token ti+1t_{i+1} with cross-entropy. The sequence is shifted by one: the input to the model is [t1,…,tT−1][t_1, \ldots, t_{T-1}] and the targets are [t2,…,tT][t_2, \ldots, t_T], 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 [t1,…,tT][t_1, \ldots, t_T]:

  1. Run a forward pass. The logits at position TT encode the distribution for tT+1t_{T+1}.
  2. Sample tT+1t_{T+1} from this distribution.
  3. Append tT+1t_{T+1} to the sequence.
  4. 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 τ>0\tau > 0:

P(t)=softmax ⁣(logitsτ)P(t) = \text{softmax}\!\left(\frac{\mathbf{logits}}{\tau}\right)

τ=1\tau = 1 leaves the model's learned distribution unchanged. τ<1\tau < 1 concentrates probability on the highest-scoring tokens, producing more predictable output. τ>1\tau > 1 spreads probability more evenly, producing more varied output.

Top-kk sampling. Before softmax, all logits below the kk-th highest are set to −∞-\infty. Only the kk most likely candidates survive. GPT-2's original paper used k=40k = 40.

Top-pp (nucleus) sampling. Instead of a fixed kk, retain the smallest set of tokens whose cumulative probability exceeds pp, and sample from that set. At p=0.9p = 0.9 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 (D=768D = 768, H=12H = 12, N=12N = 12, V=50,257V = 50{,}257, Tmax⁡=1,024T_{\max} = 1{,}024):

ComponentParameters
Token embedding E\mathbf{E}50,257×768≈38.6 M50{,}257 \times 768 \approx 38.6\text{ M}
Positional embedding P\mathbf{P}1,024×768≈0.8 M1{,}024 \times 768 \approx 0.8\text{ M}
12 transformer blocks (≈12D2\approx 12D^2 each)12×7.1 M≈85.1 M12 \times 7.1\text{ M} \approx 85.1\text{ M}
Final LayerNorm (2D2D)1,5361{,}536
LM head (tied to E\mathbf{E})00 (shared)
Total≈124 M\approx 124\text{ M}

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 12D212D^2 parameters, which grows quadratically with DD 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 NN of these blocks and training on next-token prediction over a large text corpus is, in its essentials, how modern language models are built.