Build a GPT from scratch¶
Everything in this track meets here. You will build a GPT in plain NumPy, including every backward pass, check each gradient numerically, and train it on Shakespeare until it beats every n-gram model; then you will see the same model in 90 lines of PyTorch and exactly what changes on the way to GPT-2 and to modern LLMs.
10,000 ft
"GPT" is a decoder-only transformer trained with the language-modelling objective. The architecture that runs frontier models in 2026 is this one with a handful of refinements (different normalisation, rotary positions, gated MLPs, grouped key-value heads, mixtures of experts). Building it once, end to end, turns the earlier pages (attention, multi-head attention, the block, positional encoding) from separate ideas into one program you understand line by line. Every later topic, from KV caching to LoRA to interpretability, modifies or inspects this program.
2,000 ft
Token ids become vectors (a token embedding plus a position embedding). A stack of \(L\) identical blocks updates those vectors in place: each block lets every position read from earlier positions (causal self-attention), then transforms each position independently (an MLP), each sub-layer wrapped in LayerNorm and a residual connection. A final LayerNorm and a linear layer map every position's vector to logits over the vocabulary. Train with cross-entropy on the next token and AdamW; sample by feeding the model its own output.
- Data: a long stream of token ids; random windows of length \(T\); targets are inputs shifted by one.
- Embed: look up a \(d\)-vector per token and per position; add them.
- Blocks: attention mixes information across positions; the MLP processes each position; residuals carry the stream.
- Head: LayerNorm then a \(d\times V\) matrix gives next-token logits at every position.
- Train: cross-entropy, backprop, AdamW, warm-up and cosine decay.
- Generate: sample a token, append it, run again.
Ground level¶
The plan¶
We build in four files, each short enough to type in:
| file | what it does | lines |
|---|---|---|
engine.py |
a tiny reverse-mode autodiff for NumPy arrays, with a hand-derived backward for each operation | 67 |
model.py |
the GPT: parameters, attention, blocks | 34 |
gradcheck.py |
compares every analytic gradient with finite differences | 20 |
train.py |
data, AdamW, learning-rate schedule, evaluation, sampling | 47 |
Why not just use PyTorch? You will, at the end. But writing the backward passes yourself is the only
way to know, rather than believe, what loss.backward() does inside a transformer: how the gradient
flows through a softmax, why LayerNorm's backward has three terms, where the residual stream sends
gradient. The engine is in the spirit of Karpathy's micrograd,
lifted from scalars to arrays.
Data: characters and windows¶
We use Tiny Shakespeare (1,115,394 characters) with a character-level tokeniser: the 65 distinct characters are the vocabulary. This keeps the focus on the model; a real GPT uses a BPE tokeniser with a vocabulary of 50k to 250k tokens. The first 90% is training data, the last 10% validation.
A training example is a random window of \(T=64\) characters, and its targets are the same window shifted one character to the right. Every position is a prediction, so one window gives 64 training signals. A batch stacks \(B=32\) windows: inputs and targets both have shape \((32, 64)\).
The model, layer by layer¶
Our configuration is \(V=65\), context \(T=64\), width \(d=96\), \(L=3\) blocks, \(H=4\) heads of size 24. GPT-2 small is the same program with \(V=50{,}257\), \(T=1024\), \(d=768\), \(L=12\), \(H=12\).
| stage | operation | output shape (ours) | parameters (ours) |
|---|---|---|---|
| token embedding | row lookup in \(W_\text{te}\in\mathbb{R}^{V\times d}\) | (32, 64, 96) | 6,240 |
| position embedding | row lookup in \(W_\text{pe}\in\mathbb{R}^{T\times d}\), added | (32, 64, 96) | 6,144 |
| per block: LayerNorm 1 | normalise each position's vector; scale and shift | (32, 64, 96) | 192 |
| per block: QKV projection | \(X W_{qkv} + b\), split into 4 heads | 3 × (32, 4, 64, 24) | 27,936 |
| per block: attention | \(\operatorname{softmax}(QK^\top/\sqrt{24} + \text{mask})V\) | (32, 4, 64, 24) | 0 |
| per block: output projection | merge heads, \(Y W_o + b\), add to residual | (32, 64, 96) | 9,312 |
| per block: LayerNorm 2 | as above | (32, 64, 96) | 192 |
| per block: MLP | \(\operatorname{GELU}(X W_1 + b_1)W_2 + b_2\), \(d\to4d\to d\), add to residual | (32, 64, 96) | 74,208 |
| final LayerNorm | (32, 64, 96) | 192 | |
| head | \(X W_\text{head}\) | (32, 64, 65) | 6,240 |
Each block has 111,840 parameters; three blocks plus embeddings, final LayerNorm and head give 354,336. (We use a separate head matrix; GPT-2 ties it to the token embedding, which saves \(Vd\) parameters, a large saving when \(V=50{,}257\).)
Counting parameters at any size¶
Almost all parameters sit in the four weight matrices of each block: \(3d^2\) (QKV) \(+ d^2\) (output) \(+ 8d^2\) (MLP) \(= 12d^2\). So
The exact count, with biases and LayerNorms, reproduces the published GPT-2 sizes to the parameter (code in Build it):
| model | \(d\) | \(L\) | exact parameters | \(12Ld^2\) |
|---|---|---|---|---|
| GPT-2 small | 768 | 12 | 124,439,808 | 84.9M |
| GPT-2 medium | 1024 | 24 | 354,823,168 | 302.0M |
| GPT-2 large | 1280 | 36 | 774,030,080 | 707.8M |
| GPT-2 XL | 1600 | 48 | 1,557,611,200 | 1,474.6M |
At small sizes the embeddings are a large share (39.4M of GPT-2 small's 124M); at large sizes the \(12Ld^2\) term dominates. This is exactly the embedding-counting subtlety that distorted the early scaling laws.
Initialisation: three choices that matter¶
- Small weights (\(\mathcal{N}(0, 0.02^2)\), GPT-2's choice). Logits start near zero, so the first loss is \(\approx\ln V\). Our run starts at 4.163 against \(\ln 65 = 4.174\): a passed sanity check.
- Shrink the residual-branch outputs by \(1/\sqrt{2L}\) (GPT-2 scales them by \(1/\sqrt{N}\) with \(N\) the number of residual layers). Each block adds to the residual stream twice, so without this the stream's variance grows with depth.
- LayerNorm gains at 1, biases at 0. Each sub-layer initially sees normalised inputs.
Training: AdamW, warm-up, cosine decay¶
The optimiser is AdamW (\(\beta_1=0.9\), \(\beta_2=0.95\), weight decay 0.1 on weight matrices only; see Optimisers). The learning rate warms up linearly for 100 steps to \(3\times10^{-3}\), then decays along a cosine to 10% of the peak. Warm-up protects the first steps, when Adam's second-moment estimates are still noisy; the decay lets the model settle into a minimum at the end.
What the training run looks like¶
Three thousand steps of batch 32 × 64 characters (6.1M tokens, about 6 passes over the training text) took about six minutes on two CPU threads. By the \(6ND\) rule that is \(6\times354{,}336\times6.1\times10^6\approx1.3\times10^{13}\) FLOPs, about \(4\times10^{-11}\) of GPT-3's training compute. Validation loss on held-out text:
parameters: 354,336
step 0 val loss 4.163 (1s)
step 500 val loss 2.022 (59s)
step 1000 val loss 1.848 (138s)
step 1500 val loss 1.735 (224s)
step 2000 val loss 1.651 (266s)
step 2500 val loss 1.601 (310s)
step 3000 val loss 1.612 (349s)
The 4-gram model needed a table of 18 million counts and saw only 3 characters of context; the transformer uses 354k parameters, sees 64 characters, and generalises across contexts it has never seen. A sample at temperature 1 after training:
POLIXENES:
Held sir?
Sevincates.
CLAUDIO:
Farewell, I have you untreatistance;
And they of King Romeo's further's s
It has learned the format (speaker names in capitals, line breaks, verse-like rhythm), common words, apostrophes and punctuation, and real character names, while inventing words like "untreatistance". That is about what 1.6 nats per character buys. Decoding uses this exact model to compare greedy, temperature, top-p and min-p.
From toy to GPT-2 to a 2026 LLM¶
The program does not change shape as it grows; only the numbers and a few components do.
| this page | GPT-2 (2019) | typical open LLM, 2024–2026 | |
|---|---|---|---|
| tokeniser | 65 characters | byte-level BPE, 50,257 | BPE, ~128k–256k (Tokenisation) |
| positions | learned absolute | learned absolute, 1,024 | rotary (RoPE), 8k–128k+ (Positional encoding) |
| normalisation | pre-LayerNorm | pre-LayerNorm + final LN | pre-RMSNorm (Zhang and Sennrich, 2019) |
| MLP | GELU, \(4d\) | GELU, \(4d\) | SwiGLU (Shazeer, 2020) |
| attention heads | 4 full heads | 12–25 full heads | grouped-query attention (Ainslie et al., 2023) |
| biases | yes | yes | usually none |
| output head | separate | tied to token embedding | tied or separate |
| feed-forward | dense | dense | often mixture of experts (MoE) |
LLaMA's paper lists three of these changes explicitly (pre-normalisation with RMSNorm, SwiGLU, rotary embeddings; Touvron et al., 2023); Llama 3 adds grouped-query attention with 8 key-value heads and a document-boundary attention mask (Llama Team, 2024).
Reproducing GPT-2 small itself is now a weekend project: Karpathy's build-nanogpt trains the 124M model on 10B tokens of FineWeb-Edu in about an hour for roughly USD 10 of cloud GPU time (as stated in its README). By \(6ND\) that run is \(6\times1.24\times10^8\times10^{10}\approx7.4\times10^{18}\) FLOPs.
First principles¶
Why each piece is there¶
Take any component away and something specific breaks. Reasoning through each is the fastest way to understand the architecture.
- Causal mask. Without it, position \(t\) attends to \(t+1\) and copies the answer; training loss drops towards zero and the model is useless for generation. The mask makes all \(T\) predictions honest in one pass.
- Position embeddings. Attention is a weighted average over a set: permute the inputs and the outputs permute the same way. Without position information a bidirectional transformer cannot tell "dog bites man" from "man bites dog". A causal model is less blind, because the number of visible tokens leaks position, and Haviv et al. (2022) showed causal LMs without positional encodings still learn positional information. Explicit positions remain standard because they work better and extend more predictably.
- Residual connections. Each block computes \(x + f(x)\), so the gradient of the loss with respect to an early layer includes an identity path straight from the top (Residual networks, He et al., 2015). The vector \(x\) flowing through the stack is the residual stream: every attention head and MLP reads from it and writes an update into it. Interpretability work treats it as the model's working memory.
- Pre-LayerNorm. Normalising the input of each sub-layer (rather than the sum after the residual, as in the original transformer) keeps the residual path an identity and makes deep stacks trainable without delicate warm-up; Xiong et al. (2020) analyse why post-LN gradients near the output are large at initialisation.
- Attention and MLP, alternating. Attention is the only place where positions exchange information; it is linear in the values given the weights. The MLP is where per-position nonlinear computation happens and, empirically, where much factual association is stored (Meng et al., 2022). A stack of only one kind fails: attention-only cannot compute much per token; MLP-only cannot move information between tokens.
- Multiple heads. One softmax produces one weighted average per position. Several heads let a position attend to several places for several reasons (previous token, matching bracket, subject of the sentence) at the same cost, by splitting \(d\) into \(H\) subspaces (Multi-head attention).
- The \(1/\sqrt{d_k}\) scale. Dot products of random \(d_k\)-dimensional vectors have variance \(\propto d_k\); unscaled, the softmax saturates and its gradient vanishes (Attention).
Why it trains at all: the gradient paths¶
Follow \(\partial\mathcal{L}/\partial x\) backwards through one block: \(x_{\text{out}} = x + f(x)\) gives \(\partial\mathcal{L}/\partial x = \partial\mathcal{L}/\partial x_\text{out}\,(I + \partial f/\partial x)\). The identity term means every block's input receives the full gradient from above plus whatever the block contributes. With the residual-output initialisation shrunk by \(1/\sqrt{2L}\), each \(f\) starts close to zero, so at step 0 the whole network is close to "embedding → head", a bigram model, and depth is switched on gradually as the branch weights grow. Our loss curve shows exactly this: it drops to bigram level (2.48) almost immediately, then keeps going.
The maths¶
Forward pass, with shapes¶
For one sequence (drop the batch index), \(X^{(0)} = E_{\text{tok}}[x_{1:T}] + E_{\text{pos}}[1{:}T]\in\mathbb{R}^{T\times d}\). For each block \(\ell\):
and finally \(Z = \operatorname{LN}_f(X)\,W_\text{head}\in\mathbb{R}^{T\times V}\), \(\mathcal{L} = -\frac1T\sum_t\log\operatorname{softmax}(Z_t)_{x_{t+1}}\).
The backward passes the engine implements¶
Each operation's backward takes the upstream gradient \(G = \partial\mathcal{L}/\partial(\text{output})\) and returns gradients for its inputs.
| operation | forward | backward |
|---|---|---|
| matmul | \(C = AB\) | \(\partial A = G B^\top,\ \partial B = A^\top G\) |
| add (broadcast) | \(C = A + \mathbf{b}\) | $\partial A = G, \partial\mathbf{b} = $ sum of \(G\) over broadcast axes |
| embedding | \(C = W[\text{idx}]\) | scatter-add \(G\) into the rows of \(\partial W\) named by idx |
| GELU (tanh form) | \(y = \tfrac12 x(1+\tanh u)\), \(u = k(x + 0.044715x^3)\) | \(\partial x = G\left[\tfrac12(1+\tanh u) + \tfrac12 x(1-\tanh^2u)\,k(1+0.134145x^2)\right]\) |
| softmax (row) | \(p = \operatorname{softmax}(s)\) | \(\partial s = p\odot(G - \langle G, p\rangle)\) |
| cross-entropy | \(\ell = -\log p_y\) | \(\partial z = (p - \mathbf{e}_y)/N\) |
| LayerNorm | \(y = \gamma\odot\hat x + \beta\) | see derivation |
Derivation: the softmax backward, and why masked positions get zero gradient
For one row, \(p_i = e^{s_i}/\sum_k e^{s_k}\) has Jacobian \(\partial p_i/\partial s_j = p_i(\delta_{ij} - p_j)\). The chain rule gives
In vector form, \(\partial s = p\odot(G - \langle G,p\rangle\mathbf{1})\): an \(O(T)\) computation per row, never forming the \(T\times T\) Jacobian. Masked positions have \(p_j = 0\) (from \(e^{-\infty}\)), so their gradient is exactly zero and the future never receives credit. The scale \(1/\sqrt{d_h}\) applied before the softmax multiplies this gradient by the same factor on the way back.
Derivation: the LayerNorm backward
For one position's vector \(x\in\mathbb{R}^d\): \(\mu = \frac1d\sum_i x_i\), \(\sigma^2 = \frac1d\sum_i(x_i-\mu)^2\), \(\hat x = (x-\mu)/\sqrt{\sigma^2+\epsilon}\), \(y = \gamma\odot\hat x + \beta\). Parameter gradients are immediate: \(\partial\gamma = \sum_{\text{positions}} G\odot\hat x\), \(\partial\beta = \sum_{\text{positions}} G\). Let \(g = G\odot\gamma\) (the gradient arriving at \(\hat x\)) and \(r = 1/\sqrt{\sigma^2+\epsilon}\). Since \(\hat x\) depends on \(x\) directly, through \(\mu\) and through \(\sigma^2\):
using \(\partial\mu/\partial x_j = 1/d\) and \(\partial\sigma^2/\partial x_j = \frac2d(x_j-\mu)\). Contracting with \(g\):
Three terms: the direct path, minus the part that would shift the mean, minus the part that would
change the scale. The output of LayerNorm cannot change under shifts or rescaling of \(x\), so the
gradient has no component along those directions: it is orthogonal to \(\mathbf{1}\) and to \(\hat x\).
This is the line (d - d.mean(-1) - xhat * (d * xhat).mean(-1)) / sqrt(var + eps) in engine.py.
Derivation: the attention backward, end to end
For one head with \(S = QK^\top/\sqrt{d_h}\), \(P = \operatorname{softmax}(S+M)\), \(O = PV\), and upstream \(G_O\):
The engine never writes these out: they fall out of composing matmul, transpose and softmax backwards, which is the point of reverse-mode autodiff. FlashAttention computes exactly these expressions in tiles without storing \(P\) (KV cache and efficient attention).
AdamW¶
With gradient \(g_t\), moments \(m_t = \beta_1 m_{t-1} + (1-\beta_1)g_t\) and \(v_t = \beta_2 v_{t-1} + (1-\beta_2)g_t^2\), bias corrections \(\hat m_t = m_t/(1-\beta_1^t)\), \(\hat v_t = v_t/(1-\beta_2^t)\), the update is
with the weight decay \(\lambda\theta\) decoupled from the adaptive scaling (Loshchilov and Hutter, 2017); Adam itself is Kingma and Ba, 2014. Each parameter needs two extra arrays, so optimiser state is twice the model's size: one reason training needs far more memory than inference (Compute maths).
Build it¶
Save Tiny Shakespeare next to the code (curl -O https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt).
NumPy only.
1. engine.py — reverse-mode autodiff for arrays. Every operation returns a node holding its
output, its parents and a closure that pushes the upstream gradient to the parents. backward
visits nodes in reverse topological order.
import numpy as np
class T:
"""An array plus its gradient and the recipe for pushing gradients to its parents."""
def __init__(self, data, parents=(), back=None):
self.data, self.parents, self.back = data, parents, back
self.grad = np.zeros_like(data)
def acc(t, g): # add g into t.grad, undoing broadcasting
while g.ndim > t.data.ndim: g = g.sum(0)
for i, n in enumerate(t.data.shape):
if n == 1 and g.shape[i] != 1: g = g.sum(i, keepdims=True)
t.grad += g
def op(data, parents, back):
out = T(data, parents); out.back = lambda: back(out.grad); return out
def add(a, b): return op(a.data + b.data, (a, b), lambda g: (acc(a, g), acc(b, g)))
def matmul(a, b): return op(a.data @ b.data, (a, b), lambda g: (
acc(a, g @ b.data.swapaxes(-1, -2)), acc(b, a.data.swapaxes(-1, -2) @ g)))
def reshape(a, *s): return op(a.data.reshape(s), (a,), lambda g: acc(a, g.reshape(a.data.shape)))
def transpose(a, *ax): return op(a.data.transpose(ax), (a,), lambda g: acc(a, g.transpose(np.argsort(ax))))
def take(a, i): # a[i] along the first axis
def back(g): z = np.zeros_like(a.data); z[i] = g; acc(a, z)
return op(a.data[i], (a,), back)
def embed(W, idx):
return op(W.data[idx], (W,), lambda g: np.add.at(W.grad, idx, g))
def gelu(a): # tanh approximation, as in GPT-2
x, k = a.data, 0.7978845608 # k = sqrt(2/pi); a Python float keeps float32
t = np.tanh(k * (x + 0.044715 * x * x * x))
dy = 0.5 * (1 + t) + 0.5 * x * (1 - t * t) * k * (1 + 0.134145 * x * x)
return op(0.5 * x * (1 + t), (a,), lambda g: acc(a, g * dy))
def layernorm(a, w, b, eps=1e-5):
mu, var = a.data.mean(-1, keepdims=True), a.data.var(-1, keepdims=True)
xhat = (a.data - mu) / np.sqrt(var + eps)
def back(g):
acc(w, g * xhat); acc(b, g)
d = g * w.data
acc(a, (d - d.mean(-1, keepdims=True) - xhat * (d * xhat).mean(-1, keepdims=True))
/ np.sqrt(var + eps))
return op(xhat * w.data + b.data, (a, w, b), back)
def causal_softmax(s, scale): # s: (B, H, T, T) raw scores
n = s.data.shape[-1]
z = np.where(np.tril(np.ones((n, n), bool)), s.data * scale, -np.inf)
p = np.exp(z - z.max(-1, keepdims=True)); p /= p.sum(-1, keepdims=True)
return op(p, (s,), lambda g: acc(s, scale * p * (g - (g * p).sum(-1, keepdims=True))))
def cross_entropy(logits, y): # logits (B, T, V), y (B, T) ints
z = logits.data - logits.data.max(-1, keepdims=True)
p = np.exp(z); p /= p.sum(-1, keepdims=True)
loss = -np.log(np.take_along_axis(p, y[..., None], -1)).mean()
def back(g):
d = p.copy(); np.put_along_axis(d, y[..., None], np.take_along_axis(p, y[..., None], -1) - 1, -1)
acc(logits, g * d / y.size)
return op(np.array(loss), (logits,), back)
def backward(root):
order, seen = [], set()
def visit(t):
if id(t) not in seen:
seen.add(id(t)); [visit(p) for p in t.parents]; order.append(t)
visit(root); root.grad = np.ones_like(root.data)
for t in reversed(order):
if t.back: t.back()
NumPy 2 type promotion will quietly slow you down
A first version used k = np.sqrt(2 / np.pi). That is a NumPy float64 scalar, and under NumPy 2's
promotion rules it upcasts every float32 array it touches, so GELU ran in double precision and
training was 2.3× slower (0.145 s against 0.062 s per step). Plain Python floats are "weak" and keep
the array's dtype. Check .dtype of your activations once.
2. model.py — the GPT.
import numpy as np
from engine import T, add, matmul, reshape, transpose, take, embed, gelu, layernorm, causal_softmax
def init_gpt(V, ctx, d, n_layer, n_head, seed=0, dtype=np.float32):
rng = np.random.default_rng(seed)
w = lambda *s, std=0.02: T(rng.normal(0, std, s).astype(dtype))
zeros, ones = (lambda *s: T(np.zeros(s, dtype))), (lambda *s: T(np.ones(s, dtype)))
proj_std = 0.02 / np.sqrt(2 * n_layer) # GPT-2: shrink residual-branch outputs
P = {"wte": w(V, d), "wpe": w(ctx, d), "lnf_w": ones(d), "lnf_b": zeros(d), "head": w(d, V)}
for l in range(n_layer):
P |= {f"{l}.ln1_w": ones(d), f"{l}.ln1_b": zeros(d), f"{l}.ln2_w": ones(d), f"{l}.ln2_b": zeros(d),
f"{l}.qkv": w(d, 3 * d), f"{l}.qkv_b": zeros(3 * d),
f"{l}.proj": w(d, d, std=proj_std), f"{l}.proj_b": zeros(d),
f"{l}.fc": w(d, 4 * d), f"{l}.fc_b": zeros(4 * d),
f"{l}.out": w(4 * d, d, std=proj_std), f"{l}.out_b": zeros(d)}
return P
def attention(x, P, l, n_head): # x: (B, T, d)
B, Tn, d = x.data.shape; hs = d // n_head
qkv = add(matmul(x, P[f"{l}.qkv"]), P[f"{l}.qkv_b"]) # (B, T, 3d)
qkv = transpose(reshape(qkv, B, Tn, 3, n_head, hs), 2, 0, 3, 1, 4) # (3, B, H, T, hs)
q, k, v = take(qkv, 0), take(qkv, 1), take(qkv, 2) # each (B, H, T, hs)
att = causal_softmax(matmul(q, transpose(k, 0, 1, 3, 2)), hs ** -0.5) # (B, H, T, T)
y = reshape(transpose(matmul(att, v), 0, 2, 1, 3), B, Tn, d) # merge heads
return add(matmul(y, P[f"{l}.proj"]), P[f"{l}.proj_b"])
def gpt(idx, P, n_layer, n_head): # idx: (B, T) token ids -> logits (B, T, V)
Tn = idx.shape[1]
x = add(embed(P["wte"], idx), embed(P["wpe"], np.arange(Tn)))
for l in range(n_layer):
x = add(x, attention(layernorm(x, P[f"{l}.ln1_w"], P[f"{l}.ln1_b"]), P, l, n_head))
h = gelu(add(matmul(layernorm(x, P[f"{l}.ln2_w"], P[f"{l}.ln2_b"]), P[f"{l}.fc"]), P[f"{l}.fc_b"]))
x = add(x, add(matmul(h, P[f"{l}.out"]), P[f"{l}.out_b"]))
return matmul(layernorm(x, P["lnf_w"], P["lnf_b"]), P["head"])
3. gradcheck.py — trust nothing until it is checked. In float64, perturb five random entries of
every parameter tensor by \(\pm10^{-5}\) and compare the central difference with the analytic gradient.
import numpy as np
from engine import cross_entropy, backward
from model import init_gpt, gpt
V, ctx, d, L, H = 11, 8, 16, 2, 4
P = init_gpt(V, ctx, d, L, H, seed=1, dtype=np.float64)
for t in P.values(): t.data += np.random.default_rng(2).normal(0, 0.1, t.data.shape) # break symmetry
rng = np.random.default_rng(3)
x, y = rng.integers(0, V, (2, ctx)), rng.integers(0, V, (2, ctx))
loss = cross_entropy(gpt(x, P, L, H), y); backward(loss)
worst = 0.0
for name, t in P.items():
for i in rng.choice(t.data.size, size=min(5, t.data.size), replace=False):
j = np.unravel_index(i, t.data.shape); old = t.data[j]; e = 1e-5
t.data[j] = old + e; lp = cross_entropy(gpt(x, P, L, H), y).data
t.data[j] = old - e; lm = cross_entropy(gpt(x, P, L, H), y).data
t.data[j] = old
num = (lp - lm) / (2 * e)
worst = max(worst, abs(num - t.grad[j]) / max(1e-8, abs(num) + abs(t.grad[j])))
print(f"loss {loss.data:.4f}; checked {len(P)} parameter tensors; worst relative error {worst:.1e}")
A relative error around \(10^{-7}\) in float64 means every backward pass is right. A bug typically shows as an error of \(10^{-2}\) or worse on the tensors downstream of the broken operation.
4. train.py — train and sample. This produced the log and sample shown above.
import numpy as np, time
from engine import cross_entropy, backward
from model import init_gpt, gpt
text = open("input.txt").read()
chars = sorted(set(text)); V = len(chars)
stoi = {c: i for i, c in enumerate(chars)}
data = np.array([stoi[c] for c in text]); n = int(0.9 * len(data))
train, val = data[:n], data[n:]
ctx, d, L, H, B, steps = 64, 96, 3, 4, 32, 3000
P = init_gpt(V, ctx, d, L, H)
print(f"parameters: {sum(t.data.size for t in P.values()):,}")
rng = np.random.default_rng(0)
def batch(src):
i = rng.integers(0, len(src) - ctx - 1, B)
return np.stack([src[j:j + ctx] for j in i]), np.stack([src[j + 1:j + ctx + 1] for j in i])
def lr_at(s, peak=3e-3, warm=100): # linear warm-up, then cosine decay to 10%
if s < warm: return peak * (s + 1) / warm
return peak * (0.1 + 0.45 * (1 + np.cos(np.pi * (s - warm) / (steps - warm))))
m = {k: np.zeros_like(t.data) for k, t in P.items()}
v = {k: np.zeros_like(t.data) for k, t in P.items()}
b1, b2, wd, t0 = 0.9, 0.95, 0.1, time.time()
for s in range(steps + 1):
if s % 500 == 0:
vl = np.mean([cross_entropy(gpt(x, P, L, H), y).data for x, y in (batch(val) for _ in range(20))])
print(f"step {s:5d} val loss {vl:.3f} ({time.time() - t0:.0f}s)")
if s == steps: break
x, y = batch(train)
for t in P.values(): t.grad[...] = 0
loss = cross_entropy(gpt(x, P, L, H), y); backward(loss)
lr = float(lr_at(s))
for k, t in P.items(): # AdamW; decay only weight matrices
m[k] = b1 * m[k] + (1 - b1) * t.grad
v[k] = b2 * v[k] + (1 - b2) * t.grad * t.grad
mh, vh = m[k] / (1 - b1 ** (s + 1)), v[k] / (1 - b2 ** (s + 1))
t.data -= lr * (mh / (np.sqrt(vh) + 1e-8) + (wd * t.data if t.data.ndim == 2 else 0))
np.savez("gpt_np.npz", **{k: t.data for k, t in P.items()})
idx = np.array([[stoi["\n"]]]) # sample 400 characters, temperature 1
for _ in range(400):
logits = gpt(idx[:, -ctx:], P, L, H).data[0, -1]
p = np.exp(logits - logits.max()); p /= p.sum()
idx = np.concatenate([idx, [[rng.choice(V, p=p)]]], axis=1)
print("".join(chars[i] for i in idx[0]))
Output: the log and sample shown in What the training run looks like.
Set VECLIB_MAXIMUM_THREADS=2 (macOS) or OMP_NUM_THREADS=2 to keep it polite on a shared machine.
5. Parameter counts for the GPT-2 family.
def gpt2_params(V, ctx, d, L, tied=True):
emb = V * d + ctx * d # token + position embeddings
attn = d * 3 * d + 3 * d + d * d + d # qkv weights+biases, output projection
mlp = d * 4 * d + 4 * d + 4 * d * d + d # up and down projections
ln = 2 * (2 * d) # two LayerNorms (gain + bias)
head = 0 if tied else d * V # GPT-2 reuses wte as the output layer
return emb + L * (attn + mlp + ln) + 2 * d + head
for name, d, L in [("gpt2", 768, 12), ("gpt2-medium", 1024, 24), ("gpt2-large", 1280, 36), ("gpt2-xl", 1600, 48)]:
N = gpt2_params(50257, 1024, d, L)
print(f"{name:12s} d={d:4d} L={L:2d} params {N:>13,} 12*L*d^2 = {12 * L * d * d / 1e6:6.1f}M")
print(f"this page's NumPy GPT: {gpt2_params(65, 64, 96, 3, tied=False):,}")
gpt2 d= 768 L=12 params 124,439,808 12*L*d^2 = 84.9M
gpt2-medium d=1024 L=24 params 354,823,168 12*L*d^2 = 302.0M
gpt2-large d=1280 L=36 params 774,030,080 12*L*d^2 = 707.8M
gpt2-xl d=1600 L=48 params 1,557,611,200 12*L*d^2 = 1474.6M
this page's NumPy GPT: 354,336
6. The same model in PyTorch. This is the version to scale up. It is standard PyTorch (2.x) and mirrors nanoGPT's model; it was syntax-checked but not run here, since PyTorch is not installed on the machine this page was written on. With these settings (6 layers, 6 heads, \(d=384\), context 256, dropout 0.2, 5,000 steps), nanoGPT's README reports a best validation loss of 1.4697 after about 3 minutes on one A100 GPU, so expect a number in that region on a GPU, and patience on a laptop.
import math, torch, torch.nn as nn, torch.nn.functional as F
class Block(nn.Module):
def __init__(self, d, n_head, dropout):
super().__init__()
self.ln1, self.ln2 = nn.LayerNorm(d), nn.LayerNorm(d)
self.qkv, self.proj = nn.Linear(d, 3 * d), nn.Linear(d, d)
self.mlp = nn.Sequential(nn.Linear(d, 4 * d), nn.GELU(approximate="tanh"),
nn.Linear(4 * d, d), nn.Dropout(dropout))
self.n_head, self.dropout = n_head, dropout
def forward(self, x): # x: (B, T, d)
B, T, d = x.shape
q, k, v = self.qkv(self.ln1(x)).split(d, dim=2)
q, k, v = (t.view(B, T, self.n_head, d // self.n_head).transpose(1, 2) for t in (q, k, v))
y = F.scaled_dot_product_attention(q, k, v, is_causal=True,
dropout_p=self.dropout if self.training else 0.0)
x = x + F.dropout(self.proj(y.transpose(1, 2).reshape(B, T, d)), self.dropout, self.training)
return x + self.mlp(self.ln2(x))
class GPT(nn.Module):
def __init__(self, V, ctx, d=384, n_layer=6, n_head=6, dropout=0.2):
super().__init__()
self.wte, self.wpe = nn.Embedding(V, d), nn.Embedding(ctx, d)
self.blocks = nn.ModuleList(Block(d, n_head, dropout) for _ in range(n_layer))
self.ln_f, self.head = nn.LayerNorm(d), nn.Linear(d, V, bias=False)
self.head.weight = self.wte.weight # weight tying, as in GPT-2
self.apply(self._init)
for blk in self.blocks: # scaled init of residual outputs
nn.init.normal_(blk.proj.weight, 0.0, 0.02 / math.sqrt(2 * n_layer))
nn.init.normal_(blk.mlp[2].weight, 0.0, 0.02 / math.sqrt(2 * n_layer))
@staticmethod
def _init(m): # GPT-2: N(0, 0.02) weights, zero biases
if isinstance(m, (nn.Linear, nn.Embedding)):
nn.init.normal_(m.weight, 0.0, 0.02)
if isinstance(m, nn.Linear) and m.bias is not None:
nn.init.zeros_(m.bias)
def forward(self, idx, targets=None): # idx: (B, T) token ids
x = self.wte(idx) + self.wpe(torch.arange(idx.shape[1], device=idx.device))
for blk in self.blocks:
x = blk(x)
logits = self.head(self.ln_f(x)) # (B, T, V)
if targets is None:
return logits, None
return logits, F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1))
@torch.no_grad()
def generate(self, idx, n, temperature=1.0, ctx=256):
for _ in range(n):
logits, _ = self(idx[:, -ctx:])
p = F.softmax(logits[:, -1] / temperature, dim=-1)
idx = torch.cat([idx, torch.multinomial(p, 1)], dim=1)
return idx
import math, torch
from gpt_torch import GPT # the module above, saved as gpt_torch.py
text = open("input.txt").read()
chars = sorted(set(text)); stoi = {c: i for i, c in enumerate(chars)}
data = torch.tensor([stoi[c] for c in text]); n = int(0.9 * len(data))
train, val = data[:n], data[n:]
dev = "cuda" if torch.cuda.is_available() else ("mps" if torch.backends.mps.is_available() else "cpu")
ctx, B, steps, peak, warm = 256, 64, 5000, 1e-3, 100
def batch(src):
i = torch.randint(len(src) - ctx - 1, (B,))
x = torch.stack([src[j:j + ctx] for j in i]); y = torch.stack([src[j + 1:j + ctx + 1] for j in i])
return x.to(dev), y.to(dev)
model = GPT(len(chars), ctx).to(dev)
decay = [p for p in model.parameters() if p.dim() >= 2]
no_decay = [p for p in model.parameters() if p.dim() < 2]
opt = torch.optim.AdamW([{"params": decay, "weight_decay": 0.1},
{"params": no_decay, "weight_decay": 0.0}], lr=peak, betas=(0.9, 0.99))
for s in range(steps):
lr = peak * min((s + 1) / warm, 0.1 + 0.45 * (1 + math.cos(math.pi * s / steps)))
for g in opt.param_groups: g["lr"] = lr
_, loss = model(*batch(train))
opt.zero_grad(set_to_none=True); loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0); opt.step()
if s % 500 == 0 or s == steps - 1:
model.eval()
with torch.no_grad():
vl = sum(model(*batch(val))[1].item() for _ in range(50)) / 50
model.train(); print(f"step {s:5d} train {loss.item():.3f} val {vl:.3f}")
model.eval()
start = torch.tensor([[stoi["\n"]]], device=dev)
print("".join(chars[i] for i in model.generate(start, 500)[0].tolist()))
What PyTorch adds over the NumPy version: F.scaled_dot_product_attention dispatches to a fused
FlashAttention-style kernel; dropout regularises the larger model; weight tying shares the embedding
with the head; gradient clipping guards against rare large updates; the device line uses a GPU or
Apple-silicon mps when available.
Things to try
- Ablate the mask. Replace
np.tril(...)with an all-true mask and train for 300 steps. Watch the training loss collapse while samples become garbage, then explain why. - Ablate positions. Zero
wpeand freeze it. How much worse is validation loss after 3,000 steps? Does the model still learn line lengths (a positional skill)? - Remove the residual-output scaling (
proj_std = 0.02) and use \(L=8\). Compare the first 300 steps. - Tie the head to
wte(useP["wte"]transposed as the head and dropP["head"]). Parameter count falls by 6,240; does validation loss change? - Scale it. Double \(d\) to 192 and compare the loss at equal compute rather than equal steps. Which model wins at a fixed number of FLOPs? You have just run a tiny scaling-law experiment.
- Add a KV cache to sampling: store each block's keys and values so each new character costs one position instead of \(T\). Count the matmuls saved (KV cache).
Check yourself¶
Where in a GPT do different positions exchange information, and where do they not?
Only in attention (the \(P_hV_h\) product mixes values across positions). Embeddings, LayerNorm, the MLP and the head all act on each position independently.
Why is the loss at step 0 about 4.17 for this model, and what would 30 indicate?
Small initial weights give near-zero logits, so the softmax is near uniform over 65 characters and the loss is \(\ln 65\approx4.17\). A loss of 30 means the initial logits are huge (bad initialisation or a missing scale), so the model starts out confidently wrong.
Derive the parameter count of one GPT-2 block in terms of d.
QKV: \(3d^2 + 3d\). Output projection: \(d^2 + d\). MLP: \(4d^2 + 4d\) and \(4d^2 + d\). Two LayerNorms: \(4d\). Total \(12d^2 + 13d\). For \(d=768\) that is 7,087,872 per block; ×12 = 85.05M, plus 39.4M of embeddings and the final LayerNorm, giving 124.4M.
Why does the LayerNorm gradient have three terms?
\(\hat x\) depends on \(x\) directly, through the mean and through the variance. The output is invariant to shifting or rescaling \(x\), so the gradient must be orthogonal to \(\mathbf{1}\) and to \(\hat x\); the second and third terms remove exactly those components.
With residual outputs initialised near zero, what function does the network compute at step 0, and what does that predict about the loss curve?
Approximately \(\text{head}(\text{LN}(\text{embedding}))\): a function of the current token only (plus position), i.e. a bigram-like model. So the loss should fall quickly to roughly bigram level (2.48 here) and only then use attention for more, which is what the curve shows.
Hard: training uses teacher forcing with all T positions in parallel, but generation is sequential. Why is the parallel training not cheating?
The causal mask guarantees that the computation at position \(t\) depends only on tokens \(\le t\), exactly the information available during generation. Each of the \(T\) outputs is the same function the model will compute at generation time for that prefix; computing them together is just batching.
Hard: your NumPy model's validation loss stops improving at 1.60 while training loss keeps falling. Name three changes and say which scaling-law term each attacks.
More data or augmentation (the data term \(B/D^\beta\): you are repeating the same 1M characters about 6 times); a bigger model with dropout or weight decay (the model term \(A/N^\alpha\), with regularisation to control overfitting); a longer context or a better tokeniser (changes the problem itself, lowering the achievable loss per character).
Go deeper¶
Videos and lectures
- Let's build GPT: from scratch, in code, spelled out — Andrej Karpathy. The canonical two-hour build on Tiny Shakespeare; this page's PyTorch code follows its structure.
- Let's reproduce GPT-2 (124M) — Andrej Karpathy. From the toy to a real GPT-2: mixed precision, FlashAttention, DDP, FineWeb-Edu, HellaSwag evaluation.
- Transformers, the tech behind LLMs — 3Blue1Brown. The visual intuition for embeddings, attention and the residual stream.
Code
- karpathy/nanoGPT — ~300-line
model.py; the reference for the PyTorch version above. - karpathy/build-nanogpt — The GPT-2 reproduction, commit by commit.
- karpathy/minGPT — The more educational predecessor of nanoGPT.
- karpathy/llm.c — The same model in plain C/CUDA with every backward pass written by hand: the next step after this page's engine.
Papers
- Attention Is All You Need — Vaswani et al., 2017. The original encoder-decoder; GPT keeps the decoder half.
- Improving Language Understanding by Generative Pre-Training — Radford et al., 2018. GPT-1: decoder-only pre-training.
- Language Models are Unsupervised Multitask Learners — Radford et al., 2019. GPT-2; section 2.3 lists the architectural changes used here (pre-LN, final LN, scaled residual init).
- On Layer Normalization in the Transformer Architecture — Xiong et al., 2020. Why pre-LN trains more stably than post-LN.
- LLaMA: Open and Efficient Foundation Language Models — Touvron et al., 2023. Section 2.2: the modern refinements (RMSNorm, SwiGLU, RoPE).
- Decoupled Weight Decay Regularization — Loshchilov and Hutter, 2017. AdamW.
Articles and courses
- The Annotated Transformer — Harvard NLP. The original paper as runnable code, line by line.
- The Illustrated GPT-2 — Jay Alammar. Pictures of every tensor in a decoder-only forward pass.
- Stanford CS336: Language Modeling from Scratch — Assignment 1 builds tokenizer, model and optimiser from scratch, with resource accounting.
Where this leads¶
- Project: build and train a tiny GPT — a guided project that extends this page to BPE tokens and a GPU.
- Decoding: greedy, beam, temperature, top-k, top-p — get good text out of the model you just trained.
- KV cache, FlashAttention, MQA/GQA/MLA — make generation and attention fast.
- Scaling laws — how this loss would fall if you kept growing \(N\) and \(D\).
- Instruction tuning (SFT) — how a pre-trained GPT becomes an assistant.