Project: build and train a tiny GPT¶
You will write a decoder-only transformer in about 140 lines of PyTorch, prove it is causal and trainable with four automated tests, and train it on the complete works of Shakespeare until it beats every count-based model you can build. The idea to walk away with: a GPT is a small, regular program, and almost all of the skill is in the checks you run around it.
10,000 ft
Every large language model of 2026 is, at its core, the program you build here: embed tokens, run a stack of identical blocks in which tokens exchange information through causal attention and then think alone through an MLP, and predict the next token with a softmax trained by cross-entropy (the language-modelling objective). What separates this project from a frontier model is scale, data, a subword tokeniser, and the engineering of distributed training, not a different idea. The project sits on the second rung of the project ladder: micrograd taught you how gradients flow through scalars; this teaches you how they flow through tensors, and gives you a model you will later fine-tune, quantise and sample from.
2,000 ft
Text becomes integers; the integers become a stream of (context, next character) training pairs. You first measure what simple counting achieves, so you know what "learning" must beat. Then you build attention up from a single idea, "each position takes a weighted average of the positions before it", make the weights data-dependent, split them into heads, wrap them with residual connections, LayerNorm and an MLP, and stack the result. A training loop with AdamW, warm-up and cosine decay minimises cross-entropy. At every stage an automated check tells you whether you are right: the step-0 loss, a causality test, an overfit-one-batch test, the parameter count, and finally the validation loss against known targets.
Ground level¶
What you are building, and the rules¶
The framework is PyTorch (2.1 or later; nn.LayerNorm(bias=False) needs 2.1). The project follows the arc of Andrej Karpathy's lecture Let's build GPT: from scratch, in code, spelled out and the defaults of his nanoGPT repository, so that your results can be checked against published numbers. If you want to see every backward pass written by hand instead, Build a GPT from scratch does this same model in NumPy with its own autograd engine; do that page after this one.
| file | contents | lines |
|---|---|---|
gpt.py |
data, model, training loop, sampling; two configurations | ~140 |
test_gpt.py |
parameter count, step-0 loss, causality, overfit one batch | ~30 |
baselines.py |
uniform, unigram and bigram losses (NumPy) | ~25 |
Data. Tiny Shakespeare, 1.1 MB of plays concatenated into one file:
curl -O https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt.
Hardware. Two configurations, both taken from nanoGPT so the targets are published:
| config | layers × heads × width | context | batch | steps | parameters | published result |
|---|---|---|---|---|---|---|
laptop |
4 × 4 × 128 | 64 | 12 | 2,000 | 804,096 | val loss 1.88 in about 3 minutes on a MacBook CPU |
gpu |
6 × 6 × 384 | 256 | 64 | 5,000 | 10,745,088 | val loss 1.4697 in about 3 minutes on one A100 |
Both "published result" figures are from the nanoGPT README. The parameter counts are computed below for this page's model (bias-free linears and LayerNorms, tied input and output embeddings, which is nanoGPT's design); on an Apple-silicon Mac, PyTorch's mps device runs the laptop config on the GPU and lets you try something in between.
What was run for this page. PyTorch is not installed on the machine this page was written on, so every number from NumPy below (data statistics, baselines, the attention checks, parameter counts and the step-0 loss of this exact architecture) was produced by running the code shown, and every PyTorch training number is a target taken from the published runs above. Your own run is the experiment.
Milestone 0: characters to integers to batches¶
A character-level tokeniser is a sorted list of the characters that occur:
text = open('input.txt', encoding='utf-8').read()
chars = sorted(set(text)); V = len(chars)
stoi = {c: i for i, c in enumerate(chars)}; itos = {i: c for c, i in stoi.items()}
encode = lambda s: [stoi[c] for c in s]
decode = lambda ids: ''.join(itos[i] for i in ids)
data = np.array(encode(text), dtype=np.int64)
n = int(0.9 * len(data)); train, val = data[:n], data[n:]
characters: 1,115,394 vocab: 65
vocab: "\n !$&',-.3:;?ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
encode('hii there') = [46, 47, 47, 1, 58, 46, 43, 56, 43] -> 'hii there'
train: 1,003,854 val: 111,540
The split is by position, not at random: the last 10% of the file is a different stretch of plays. A random split of overlapping windows would leak training text into validation.
A training example is a window of \(T\) consecutive ids x and the same window shifted by one, y. One window is really \(T\) examples, because the model predicts at every position:
x[0] = [56, 56, 47, 43, 42, 1, 58, 46]
y[0] = [56, 47, 43, 42, 1, 58, 46, 43]
context [56] -> target 56
context [56, 56] -> target 47
context [56, 56, 47] -> target 43
Check before moving on: decode(encode(s)) == s for any string from the file, and y[:, :-1] == x[:, 1:] for every batch.
Milestone 1: the numbers you have to beat¶
Before any neural network, measure what counting achieves on the validation split, in nats per character (cross-entropy):
These three numbers organise the whole project:
- 4.1744 = ln 65 is the loss of a model that knows nothing. Your untrained GPT must start within about 0.1 of it. A step-0 loss of 6 or 30 means the initial logits are far too large: the model is confidently wrong before it has learned anything.
- 3.35 is what character frequencies alone buy.
- 2.48 is the best any model can do that sees only the previous character. Karpathy's lecture starts with a "neural bigram" (
nn.Embedding(65, 65), whose row for the current character is the logits for the next): train it and it converges to about this number and no further, because the count table already is the maximum-likelihood solution of that model class. That is your first lesson in separating optimisation from capacity.
The language-modelling page extends this to a 4-gram model, which reaches 1.784 with a table of millions of counts. A transformer that cannot beat 1.78 has learned less than a lookup table of three characters of context.
Milestone 2: the averaging trick¶
The bigram model's problem is that position \(t\) sees only token \(t\). The cheapest way to let it see the past is to replace each position's vector by the average of all vectors up to and including it. Done with a loop, that is \(O(T^2)\) Python. Done as a matrix product with a row-normalised lower-triangular matrix, it is one call:
T = 4
x = np.array([[1.], [3.], [2.], [6.]]) # one feature per position
W = np.tril(np.ones((T, T))); W /= W.sum(1, keepdims=True)
print(W.round(3)); print("running means:", (W @ x).ravel())
S = np.where(np.tril(np.ones((T, T))) == 1, 0.0, -np.inf) # same thing via masked softmax
E = np.exp(S - S.max(1, keepdims=True)); print("softmax-mask equal:", np.allclose(E / E.sum(1, keepdims=True), W))
[[1. 0. 0. 0. ]
[0.5 0.5 0. 0. ]
[0.333 0.333 0.333 0. ]
[0.25 0.25 0.25 0.25 ]]
running means: [1. 2. 2. 3.]
softmax-mask equal: True
The second construction is the important one. Start from a matrix of scores \(S\) (here all zeros), set the scores above the diagonal to \(-\infty\), take a row-wise softmax: the \(-\infty\) entries become exactly 0 and the rest share the weight. Attention is this, with the zeros replaced by scores the network computes from the data. Uniform averaging treats every past character as equally relevant; attention lets the character after "Q" look specifically for whether the previous character was "Q".
Milestone 3: one head, then many, and the causality test¶
Each position emits three vectors from its embedding \(x_t\): a query \(q_t = x_t W_Q\) ("what am I looking for?"), a key \(k_t = x_t W_K\) ("what do I contain?") and a value \(v_t = x_t W_V\) ("what will I hand over if chosen?"). Scores are \(q_t\cdot k_s/\sqrt{d}\), masked to \(s \le t\), softmaxed, and used to average the values. The attention page derives this; here you need two facts you can test.
Fact 1: causality. Position \(t\) must be unaffected by anything after \(t\), otherwise training is cheating (the target is in the input) and generation, which never has the future, will collapse. The test is mechanical: change the last tokens and check that the earlier outputs do not move at all.
def head(x, Wq, Wk, Wv):
q, k, v = x @ Wq, x @ Wk, x @ Wv
s = q @ k.T / np.sqrt(k.shape[1])
s = np.where(np.tril(np.ones((len(x), len(x)))) == 1, s, -np.inf)
a = np.exp(s - s.max(1, keepdims=True)); a /= a.sum(1, keepdims=True)
return a @ v, a
C, hs, T = 16, 8, 6
Wq, Wk, Wv = (rng.normal(0, C**-0.5, (C, hs)) for _ in range(3))
x = rng.normal(size=(T, C))
y, a = head(x, Wq, Wk, Wv)
x2 = x.copy(); x2[4:] = rng.normal(size=(2, C)) # change the last two tokens
y2, _ = head(x2, Wq, Wk, Wv)
print("rows of attention sum to 1:", np.allclose(a.sum(1), 1))
print("max change at positions 0-3:", np.abs(y2[:4] - y[:4]).max())
print("max change at positions 4-5:", np.abs(y2[4:] - y[4:]).max().round(3))
rows of attention sum to 1: True
max change at positions 0-3: 0.0
max change at positions 4-5: 1.326
Exactly 0.0, not "small": masking is exact. If you ever see 1e-3 here, a future position is leaking, usually through a mask sliced to the wrong length or a transpose applied to the wrong axes.
Fact 2: the \(\sqrt{d}\). If the entries of \(q\) and \(k\) have unit variance, \(q\cdot k\) is a sum of \(d\) unit-variance products, so its variance is \(d\):
d= 16 var(q.k)= 16.3 var(q.k/sqrt d)=1.02
d= 64 var(q.k)= 64.5 var(q.k/sqrt d)=1.01
d=256 var(q.k)= 255.8 var(q.k/sqrt d)=1.00
Without the division, a 256-wide head produces scores with standard deviation 16, the softmax saturates to one-hot, and its gradient vanishes.
Many heads. One head computes one weighted average per position, which can express one kind of relation. \(h\) heads of size \(C/h\) run in parallel and are concatenated, costing the same as one head of size \(C\). In code you never loop over heads: one Linear(C, 3C) produces all queries, keys and values, and a reshape to (B, h, T, C/h) makes the head a batch dimension. Use the widget to see what different query positions attend to in a real sentence.
Milestone 4: the block, the model and the step-0 loss¶
Attention alone moves information between positions but computes little with it. The block alternates "communicate" (attention) and "compute" (a per-position MLP that widens to \(4C\), applies GELU, and projects back), and makes both trainable at depth with two devices from residual networks and normalisation:
The residual stream \(x\) is a highway that every block reads from and adds to; the gradient of the loss reaches the first block through the identity paths undiminished. LayerNorm goes inside the branch ("pre-LN"), which is what GPT-2 and every model since uses, because it keeps the residual stream itself unnormalised and trains stably without warm-up gymnastics (the transformer block).
Three initialisation choices matter, all from GPT-2: weights drawn from \(\mathcal N(0, 0.02^2)\); the two projections that write into the residual stream (attention proj and MLP fc2) scaled down by \(1/\sqrt{2N}\) so the stream's variance does not grow with depth; and the output head tied to the token embedding (the same \(V\times C\) matrix reads tokens in and scores them out), which saves \(VC\) parameters and is a good inductive bias.
Before training anything, the model must produce near-uniform predictions. A NumPy forward pass of exactly this architecture (same shapes, init, LayerNorm and erf-GELU) on one batch of the laptop config gives:
laptop config: 804,096 parameters (795,904 without position embeddings)
gpu config: 10,745,088 parameters (10,646,784 without position embeddings)
step-0 loss: 4.1994 ln(65) = 4.1744
Your PyTorch model must print a step-0 loss in the range 4.15 to 4.25 and exactly these parameter counts. A different count means a missing bias flag, an untied head, or a block built twice.
Milestone 5: training¶
The loop is the one from micrograd, with four upgrades that every serious training run uses:
- AdamW with \(\beta_2 = 0.99\) (tokens per step are few, so a slightly longer second-moment memory helps) and weight decay 0.1 applied to matrices only, never to LayerNorm gains (optimisers).
- Warm-up for 100 steps from 0 to the peak learning rate \(10^{-3}\), then cosine decay to \(10^{-4}\). Adam's second-moment estimates are noisy in the first steps; warm-up stops one bad early step from wrecking the initialisation.
- Gradient clipping at global norm 1.0, insurance against the occasional huge batch gradient.
- Evaluation every 250 steps on fresh random batches of both splits, with dropout off (
model.eval()), so you can see the train-val gap open.
The overfit test comes first. Before a full run, take one batch and train on it for 300 steps. A correct model and optimiser memorise 768 targets and drive the loss towards zero. If they cannot, no amount of data will help: something is disconnected (a detach, a frozen parameter, a learning rate of zero, a loss computed on the wrong axis). It is the single most valuable test in deep learning, and it costs seconds.
What a healthy run looks like. With the laptop config you should see validation loss fall below the bigram's 2.48 within the first few hundred steps and finish near the published 1.88; with gpu, finish within a few hundredths of 1.47. The gpu run also shows overfitting: with 10.7M parameters and 1M training characters, train loss keeps falling well below validation while validation flattens and can turn back up. nanoGPT's config sets eval_interval = 250 with the comment "keep frequent because we'll overfit"; keep the best-validation checkpoint, not the last.
Milestone 6: sampling, and reading what the model knows¶
Generation is the forward pass in a loop: feed the context, take the logits at the last position, divide by a temperature, optionally keep only the top \(k\), sample, append, crop to the last block_size ids, repeat (decoding).
Samples are a qualitative eval, and each loss level has a recognisable signature. Near 2.5 you get the right letter frequencies and word-length rhythm but few real words. Near 1.9 you get real short words, capitalised speaker names followed by colons, and line breaks in the right places. Near 1.6 (the NumPy GPT shows a sample) you get plausible play structure with invented words. Near 1.47, most words are real and some lines scan as verse. None of it means anything: a 10M-parameter model trained on 1M characters has learned spelling, format and local syntax, not sense.
Milestone 7: scale it and measure¶
Now treat the model as an object of experiment. The cheapest experiments that teach the most:
- Width and depth sweep. Train four sizes at a fixed token budget and plot final validation loss against parameter count on log axes. You will see diminishing returns, then overfitting, a small-data version of scaling laws.
- Ablations. Remove one thing at a time: the \(\sqrt{d}\), the residual connections, the LayerNorms, the position embedding, weight tying. Record the loss after a fixed number of steps. Removing the position embedding is instructive: attention is permutation-invariant, so without it the model cannot tell "ab" from "ba" within its context.
- Context length. Train with
block_size8, 32, 128, 256. The gain flattens: in Shakespeare, characters more than a line back rarely help predict the next one.
How you know you have succeeded¶
-
test_gpt.pypasses: 804,096 parameters, step-0 loss within 0.1 of ln 65, the causality test, and the overfit test. - The
laptoprun ends with validation loss at or below 1.95 (published 1.88); thegpurun at or below 1.50 (published 1.4697). - You can explain every line of
CausalSelfAttention.forward, including bothtransposecalls and why.contiguous()is there. - Without looking, you can write the parameter-count formula \(12NC^2 + VC + TC\) (plus LayerNorm gains) and use it to predict the size of GPT-2 small.
- You can name, from a loss curve alone, whether a run is under-trained, overfitting, or broken.
When it goes wrong¶
| symptom | likely cause |
|---|---|
| step-0 loss far above 4.17 | logits too large: default init on the head, missing final LayerNorm, or no \(\sqrt{d}\) |
| loss drops to near 0 within a few hundred steps | causality leak; run the causality test |
| loss stuck at 2.4 to 2.5 | the model is acting as a bigram: attention output not added to the stream, or the mask hides everything but the diagonal |
loss falls, then nan |
learning rate too high or no clipping; on mps/cuda with half precision, an overflow in the softmax |
| train falls, val rises from mid-run | overfitting; this is expected for the gpu config. More dropout, fewer steps, or more data |
| samples are a repeated character | sampling with argmax, or temperature near 0 |
RuntimeError: view size is not compatible |
view after transpose without .contiguous() |
First principles¶
Why next-character prediction teaches anything. Cross-entropy is minimised, in expectation, by the true conditional distribution \(p(x_{t+1} \mid x_{\le t})\). To approximate it well a model must capture whatever structure in the text makes the next character predictable: spelling, then word order, then format, and at larger scale facts and reasoning. The loss is a single number that keeps paying for more understanding, which is why the same objective scales from this project to frontier models (the language-modelling objective).
Why each check works. Each automated test isolates one way the program can be wrong while still running:
- The step-0 loss tests initialisation and the loss wiring together. Small random weights make logits near zero, so the softmax is near uniform and the loss is \(\ln V\). Anything else means the scale of some layer is wrong.
- The causality test tests the one property that is invisible in the loss (a leak makes the loss look better).
- The overfit test tests that every parameter is connected to the loss and the optimiser moves it. It cannot pass if the gradient is broken, and it costs a fraction of a real run.
- The parameter count tests the architecture against a formula you derived independently.
Only once all four pass does the validation loss mean anything. The order matters: a model that fails the causality test can post a spectacular validation loss.
Why the architecture has this shape. Attention is the only part where positions interact, and it is a weighted average, so it is cheap to parallelise across all \(T\) positions in training (unlike an RNN). Averages are linear in the values, so the network needs a non-linear per-position MLP to compute anything with what it gathers. Stacking many such layers needs residual paths (or the gradient decays through dozens of non-linear maps) and normalisation (or the activations' scale drifts layer by layer). Positional embeddings are needed because attention by itself treats its input as a set. Each component answers a specific failure; the ablations of milestone 7 make you watch each failure happen.
The maths¶
Shapes. Batch \(B\), context \(T\), width \(C\), heads \(h\), head size \(d = C/h\), vocabulary \(V\), layers \(N\).
Parameter count. Per block: \(W_{QKV}\) has \(3C^2\), \(W_O\) has \(C^2\), the MLP has \(4C^2 + 4C^2\), and two LayerNorm gains have \(2C\). So
For the gpu config: \(6(12\cdot384^2 + 768) + 65\cdot384 + 256\cdot384 + 384 = 10{,}621{,}440 + 24{,}960 + 98{,}304 + 384 = 10{,}745{,}088\), matching the count above. With \(V = 50{,}257\), \(T = 1{,}024\), \(C = 768\), \(N = 12\), and biases (which GPT-2 has) added back, the same formula gives GPT-2 small's 124M; the \(VC\) term alone is 38.6M of it, which is why vocabulary size matters so much for small models.
Training compute. A forward pass costs about 2 FLOPs per parameter per token (one multiply, one add), and the backward pass about twice that, giving the standard estimate \(6N_{\text{params}}D\) for \(D\) training tokens (compute maths). Attention adds about \(6NTC\) per token for the \(QK^\top\) and \(AV\) products, which is small while \(T \ll 12C\).
| \(N_{\text{params}}\) (non-embedding) | tokens \(D\) | \(6ND\) | attention extra | |
|---|---|---|---|---|
laptop |
0.79M | \(2000\times12\times64 = 1.54\)M | \(7.3\times10^{12}\) | 4% |
gpu |
10.6M | \(5000\times64\times256 = 81.9\)M | \(5.2\times10^{15}\) | 6% |
The A100's dense BF16 peak is 312 TFLOP/s, so \(5.2\times10^{15}\) FLOPs in the published three minutes is roughly 10% utilisation: a model this small cannot keep a big GPU busy, because each matrix multiply is tiny and the Python loop launches hundreds of kernels per step. That gap is exactly what torch.compile, fused kernels and larger batches attack (GPU architecture).
Why the gradient of cross-entropy with softmax is so simple
For one position with logits \(z \in \mathbb{R}^V\) and target \(y\), \(\ell = -z_y + \log\sum_j e^{z_j}\). Differentiating,
The gradient is "predicted probability minus one-hot target": it pushes down every wrong character in proportion to how much probability it got, and pulls up the right one by its missing mass. At initialisation \(p_i \approx 1/65\), so every logit gradient is tiny and the right one is about \(-0.985\). F.cross_entropy fuses the log-softmax and the negative log-likelihood so that this is computed without ever forming \(\log p\) of a tiny \(p\), which is the log-sum-exp trick.
Build it¶
The complete project. gpt.py is one file so you can read it top to bottom; python gpt.py laptop or python gpt.py gpu selects the configuration.
baselines.py: the numbers to beat (NumPy; output shown in milestone 1)
import numpy as np
text = open('input.txt', encoding='utf-8').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], dtype=np.int64)
n = int(0.9 * len(data)); train, val = data[:n], data[n:]
print(f"uniform {np.log(V):.4f}")
uni = np.bincount(train, minlength=V) + 1.0; uni /= uni.sum()
print(f"unigram {-np.log(uni[val]).mean():.4f}")
C = np.ones((V, V)) # add-one smoothed bigram counts
np.add.at(C, (train[:-1], train[1:]), 1)
P = C / C.sum(1, keepdims=True)
print(f"bigram {-np.log(P[val[:-1], val[1:]]).mean():.4f}")
gpt.py: data, model, training, sampling (PyTorch 2.1+)
"""A character-level GPT on Tiny Shakespeare. PyTorch 2.1+. Usage: python gpt.py [laptop|gpu]"""
import math, sys, time
import torch, torch.nn as nn
from torch.nn import functional as F
CONFIGS = { # laptop = nanoGPT's README CPU run; gpu = config/train_shakespeare_char.py
'laptop': dict(n_layer=4, n_head=4, n_embd=128, block_size=64, batch_size=12,
dropout=0.0, max_iters=2000, eval_iters=20),
'gpu': dict(n_layer=6, n_head=6, n_embd=384, block_size=256, batch_size=64,
dropout=0.2, max_iters=5000, eval_iters=200)}
cfg = CONFIGS[sys.argv[1] if len(sys.argv) > 1 and sys.argv[1] in CONFIGS else 'laptop']
globals().update(cfg)
lr, min_lr, warmup, eval_interval = 1e-3, 1e-4, 100, 250
device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'
torch.manual_seed(1337)
text = open('input.txt', encoding='utf-8').read()
chars = sorted(set(text)); vocab_size = len(chars)
stoi = {c: i for i, c in enumerate(chars)}; itos = dict(enumerate(chars))
encode = lambda s: [stoi[c] for c in s]
decode = lambda ids: ''.join(itos[i] for i in ids)
data = torch.tensor(encode(text), dtype=torch.long)
n = int(0.9 * len(data)); train_data, val_data = data[:n], data[n:]
def get_batch(split):
d = train_data if split == 'train' else val_data
ix = torch.randint(len(d) - block_size, (batch_size,))
x = torch.stack([d[i:i + block_size] for i in ix])
y = torch.stack([d[i + 1:i + block_size + 1] for i in ix])
return x.to(device), y.to(device)
class CausalSelfAttention(nn.Module):
def __init__(self):
super().__init__()
self.qkv = nn.Linear(n_embd, 3 * n_embd, bias=False) # all heads' q, k, v at once
self.proj = nn.Linear(n_embd, n_embd, bias=False)
self.drop = nn.Dropout(dropout)
self.register_buffer('mask', torch.tril(torch.ones(block_size, block_size, dtype=torch.bool)))
def forward(self, x):
B, T, C = x.shape
q, k, v = self.qkv(x).split(C, dim=2)
q, k, v = (t.view(B, T, n_head, C // n_head).transpose(1, 2) for t in (q, k, v)) # (B,h,T,hs)
att = (q @ k.transpose(-2, -1)) / math.sqrt(C // n_head) # (B,h,T,T)
att = att.masked_fill(~self.mask[:T, :T], float('-inf'))
att = self.drop(F.softmax(att, dim=-1))
y = (att @ v).transpose(1, 2).contiguous().view(B, T, C) # re-join heads
return self.drop(self.proj(y))
class Block(nn.Module):
def __init__(self):
super().__init__()
self.ln1, self.ln2 = nn.LayerNorm(n_embd, bias=False), nn.LayerNorm(n_embd, bias=False)
self.attn = CausalSelfAttention()
self.fc = nn.Linear(n_embd, 4 * n_embd, bias=False)
self.fc2 = nn.Linear(4 * n_embd, n_embd, bias=False)
self.drop = nn.Dropout(dropout)
def forward(self, x):
x = x + self.attn(self.ln1(x)) # tokens talk
return x + self.drop(self.fc2(F.gelu(self.fc(self.ln2(x))))) # each token thinks
class GPT(nn.Module):
def __init__(self):
super().__init__()
self.tok = nn.Embedding(vocab_size, n_embd)
self.pos = nn.Embedding(block_size, n_embd)
self.drop = nn.Dropout(dropout)
self.blocks = nn.Sequential(*[Block() for _ in range(n_layer)])
self.ln_f = nn.LayerNorm(n_embd, bias=False)
self.head = nn.Linear(n_embd, vocab_size, bias=False)
self.head.weight = self.tok.weight # weight tying
for name, p in self.named_parameters():
if p.dim() == 2: # GPT-2 init; residual projections shrunk by 1/sqrt(2 * n_layer)
std = 0.02 / math.sqrt(2 * n_layer) if name.endswith(('proj.weight', 'fc2.weight')) else 0.02
nn.init.normal_(p, mean=0.0, std=std)
def forward(self, idx, targets=None):
B, T = idx.shape
x = self.drop(self.tok(idx) + self.pos(torch.arange(T, device=idx.device)))
logits = self.head(self.ln_f(self.blocks(x))) # (B, T, V)
if targets is None:
return logits, None
return logits, F.cross_entropy(logits.view(B * T, -1), targets.view(B * T))
@torch.no_grad()
def generate(self, idx, max_new_tokens, temperature=1.0, top_k=None):
for _ in range(max_new_tokens):
logits, _ = self(idx[:, -block_size:])
logits = logits[:, -1, :] / temperature
if top_k is not None:
kth = torch.topk(logits, top_k).values[:, [-1]]
logits = logits.masked_fill(logits < kth, float('-inf'))
idx = torch.cat([idx, torch.multinomial(F.softmax(logits, dim=-1), 1)], dim=1)
return idx
def lr_at(it): # linear warm-up, cosine decay to min_lr
if it < warmup:
return lr * (it + 1) / warmup
progress = min(1.0, (it - warmup) / (max_iters - warmup))
return min_lr + 0.5 * (lr - min_lr) * (1 + math.cos(math.pi * progress))
@torch.no_grad()
def estimate_loss(model):
model.eval()
out = {s: torch.stack([model(*get_batch(s))[1] for _ in range(eval_iters)]).mean().item()
for s in ('train', 'val')}
model.train()
return out
if __name__ == '__main__':
model = GPT().to(device)
print(f"{sum(p.numel() for p in model.parameters()):,} parameters on {device}")
decay = [p for p in model.parameters() if p.dim() >= 2] # matrices decay,
no_decay = [p for p in model.parameters() if p.dim() < 2] # gains do not
opt = torch.optim.AdamW([{'params': decay, 'weight_decay': 0.1},
{'params': no_decay, 'weight_decay': 0.0}], lr=lr, betas=(0.9, 0.99))
t0 = time.time()
for it in range(max_iters + 1):
if it % eval_interval == 0 or it == max_iters:
l = estimate_loss(model)
print(f"step {it:5d} train {l['train']:.4f} val {l['val']:.4f} {time.time() - t0:5.0f}s")
if it == max_iters:
break
for g in opt.param_groups:
g['lr'] = lr_at(it)
x, y = get_batch('train')
_, loss = model(x, y)
opt.zero_grad(set_to_none=True)
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
opt.step()
torch.save(model.state_dict(), 'gpt.pt')
model.eval()
start = torch.zeros((1, 1), dtype=torch.long, device=device) # id 0 is '\n'
print(decode(model.generate(start, 500, temperature=0.8)[0].tolist()))
test_gpt.py: the four checks (run before every long training run)
"""Run with: python -m pytest -q test_gpt.py (uses the laptop config)"""
import math, torch
import gpt
def test_parameter_count():
assert sum(p.numel() for p in gpt.GPT().parameters()) == 804_096 # tied head counted once
def test_initial_loss_is_near_uniform():
torch.manual_seed(0)
_, loss = gpt.GPT()(*gpt.get_batch('train'))
assert abs(loss.item() - math.log(gpt.vocab_size)) < 0.1 # ln 65 = 4.174
def test_causality():
torch.manual_seed(0)
m = gpt.GPT().eval()
x = torch.randint(gpt.vocab_size, (1, gpt.block_size))
x2 = x.clone(); x2[0, 40:] = torch.randint(gpt.vocab_size, (gpt.block_size - 40,))
with torch.no_grad():
a, b = m(x)[0], m(x2)[0]
assert torch.allclose(a[0, :40], b[0, :40], atol=1e-5) # past unaffected by future
assert not torch.allclose(a[0, 40:], b[0, 40:], atol=1e-3)
def test_overfits_one_batch():
torch.manual_seed(0)
m = gpt.GPT(); opt = torch.optim.AdamW(m.parameters(), lr=3e-3)
x, y = gpt.get_batch('train')
for _ in range(300):
_, loss = m(x, y); opt.zero_grad(); loss.backward(); opt.step()
assert loss.item() < 0.3 # memorised 768 targets
A few lines deserve a second look. self.head.weight = self.tok.weight makes the two modules share one Parameter; model.parameters() yields it once, which is why the count is 804,096 and not 812,416. masked_fill(~mask, -inf) must come before the softmax; masking after it leaves rows that no longer sum to 1. generate crops the context to block_size because the position table has only that many rows.
Stretch goals, roughly in order of difficulty
- Use the fused kernel. Replace the four attention lines with
F.scaled_dot_product_attention(q, k, v, is_causal=True, dropout_p=dropout if self.training else 0.0). Check the causality test still passes and time a step before and after (FlashAttention and friends). - A KV cache. Make
generatekeep each layer's keys and values and feed only the newest token. Verify that the logits match the uncached version to 1e-5, then time 500 tokens both ways. - RoPE instead of learned positions. Rotate \(q\) and \(k\) by position (positional encoding); train with
block_size128 and evaluate at 256. - A BPE tokeniser. Write byte-pair encoding yourself (Karpathy's minbpe is the reference), train a 512-token vocabulary on Shakespeare and retrain. Compare losses in bits per character, not per token, or the comparison is meaningless.
- A scaling sweep. Five model sizes, three token budgets, one plot. Fit \(L(N) = aN^{-\alpha} + c\) and report \(\alpha\).
- Port to MLX and train on your Mac's GPU (on-device AI).
- Reproduce GPT-2 (124M). Follow Karpathy's four-hour Let's reproduce GPT-2 (124M) and its build-nanogpt repo: real BPE, FineWeb-Edu data, mixed precision,
torch.compile, distributed data parallel. Budget a rented 8-GPU node for a few hours. - Enter the speedrun. modded-nanogpt is a public record for training to 3.28 validation loss on FineWeb on 8×H100; the llm.c baseline took 45 minutes and, as of 2026, the record is under a minute. Reading its changelog is a course in modern training tricks.
Common misconceptions¶
- "The model learns words." It learns 65 characters' conditional statistics. Words, names and line breaks are patterns it discovers because they reduce the loss.
- "Lower training loss is better." Only validation loss measures generalisation. The
gpuconfig's training loss keeps falling long after the model has stopped improving. - "Attention looks at the whole sequence." A decoder's attention looks at the past only, and only within
block_size. Anything earlier does not exist for the model. - "Dropout makes the model better." It regularises: it helps when you are overfitting (the
gpuconfig, 0.2) and only slows learning when you are not (thelaptopconfig, 0.0). - "A transformer needs a GPU." This one trains on a laptop CPU in minutes. GPUs matter when \(6ND\) reaches \(10^{16}\) and beyond.
Check yourself¶
Your untrained model prints a loss of 4.17. Your colleague's prints 27.3. Same data. What is the most likely difference?
Their logits are large at initialisation, so the softmax is confidently wrong. Typical causes: default (uniform, wider) init on the output head with a large width, no final LayerNorm, or forgetting the \(1/\sqrt{d}\) so attention saturates and passes through large activations. A loss far above \(\ln V\) wastes the early steps undoing the bad init and can destabilise training.
Why does the neural bigram stop improving at about 2.48 however long you train it?
Its logits depend only on the current character, so the best it can represent is one next-character distribution per character: exactly the bigram table. The count model (with light smoothing) is already the maximum-likelihood solution of that class, so gradient descent can only converge to it. The limit is capacity, not optimisation; only giving the model more context can go lower.
Explain why y = (att @ v).transpose(1, 2).contiguous().view(B, T, C) needs every one of its calls.
att @ v has shape (B, h, T, d). transpose(1, 2) gives (B, T, h, d), putting each position's heads next to each other, so that the view concatenates heads per position rather than mixing positions. transpose only changes strides, so the memory is no longer laid out in that order; view requires compatible strides, hence .contiguous() (or use reshape, which copies when needed).
The causality test shows changes of 1e-7 at earlier positions on a GPU. Leak or not?
Almost certainly not a leak but floating-point non-determinism: different batch shapes can select different kernels and reduction orders, changing the last bits. A real leak shows up as changes of order 0.01 to 1. That is why the test uses atol=1e-5; in float64 on a CPU the change is exactly 0.
With the gpu config, validation loss is lowest at step 3,500 and higher at 5,000. Name three distinct fixes and what each costs.
Early stopping (keep the best checkpoint: free, but you trained steps you discard); more regularisation (higher dropout or weight decay: slows learning, a hyperparameter to tune); more data (the real fix: 1M characters is tiny for 10.7M parameters, but you need the data). Reducing model size also works but caps the achievable loss.
Use the parameter formula to estimate how much of GPT-2 small (V = 50,257, C = 768, N = 12, T = 1,024) is in the embeddings.
Token embedding \(VC = 38.6\)M, positions \(TC = 0.79\)M, blocks \(12\cdot12\cdot768^2 \approx 84.9\)M (plus small bias and gain terms). So about 31% of the 124M parameters are the token embedding table, shared with the output head by tying. Small models spend a large share of parameters on vocabulary; large ones almost none.
Hard: why might character-level loss and BPE-level loss be incomparable, and how do you compare them properly?
Loss per token measures nats per token, and a BPE token covers several characters, so per-token losses are larger even for a better model. Convert both to bits per character (or per byte): total nats over the validation set divided by its number of characters, times \(1/\ln 2\). Only then do the numbers measure the same thing: how many bits the model needs to encode the text.
Hard: estimate the training FLOPs of the gpu run and explain why measured GPU utilisation is far below peak.
\(6ND \approx 6\times10.6\text{M}\times81.9\text{M} \approx 5.2\times10^{15}\), plus about 6% for attention. In three minutes that is about 30 TFLOP/s, roughly 10% of an A100's 312 TFLOP/s BF16 peak. The matrices are small (384 wide), so each kernel is short and memory-bound, and kernel-launch and Python overhead between hundreds of small kernels per step dominate. Larger width, bigger batches, fused kernels and torch.compile raise utilisation.
Go deeper¶
Videos and lectures
- Let's build GPT: from scratch, in code, spelled out — Andrej Karpathy, 2023. The lecture this project follows, milestone for milestone. Attempt each milestone first, then watch.
- Let's reproduce GPT-2 (124M) — Andrej Karpathy, 2024. The next project: the same model at real scale, with every performance trick explained.
- Let's build the GPT Tokenizer — Andrej Karpathy. For stretch goal 4: why tokenisation causes so many LLM oddities.
- Stanford CS336: Language Modeling from Scratch — Hashimoto and Liang. The university-scale version of this project: tokeniser, transformer, optimiser and training, with no starter model code.
Papers
- Attention Is All You Need — Vaswani et al., 2017. Section 3 is the architecture you built (in its encoder-decoder form).
- Language Models are Unsupervised Multitask Learners — Radford et al., 2019 (GPT-2). Section 2.3 lists the pre-LN and init changes this project uses.
- Layer Normalization — Ba, Kiros and Hinton, 2016. The normalisation in every block, and why it is per-example rather than per-batch.
- Decoupled Weight Decay Regularization — Loshchilov and Hutter, 2017. Why AdamW and not Adam plus L2; the optimiser in your loop.
- FlashAttention — Dao et al., 2022. What
scaled_dot_product_attentiondoes on a GPU, and why attention is memory-bound.
Code
- karpathy/nanoGPT — The reference for both configs and both target losses. Now marked deprecated in favour of nanochat, but still the clearest training script.
- karpathy/ng-video-lecture — The lecture's
bigram.pyandgpt.py; diff yours against them. - karpathy/nanochat — "The best ChatGPT that $100 can buy": tokeniser, pre-training, fine-tuning, RL, evaluation and inference in one small repo. The end of this road.
- KellerJordan/modded-nanogpt — The GPT-2 training speedrun; each record is a documented, measured improvement.
Articles and notes
- The Annotated Transformer — Harvard NLP. The original paper, line by line, in PyTorch.
- LLMs from scratch — Sebastian Raschka. The book's code: a GPT built and pre-trained step by step, then fine-tuned; a slower, more explained path through the same ground.
Where this leads¶
- Build a GPT from scratch — the same model in NumPy with every backward pass by hand; the strongest test of whether you understood this one.
- Project: fine-tune a model with LoRA — the next rung: adapt a real pre-trained model instead of training a toy from zero.
- Scaling laws — turn your milestone-7 sweep into the theory that decides how frontier models are sized.
- KV cache and efficient attention — what stretch goals 1 and 2 become at production scale.