Train a tiny GPT and understand every line
For engineers
Tokenizer, attention, gradient descent and a PyTorch training loop for a tiny GPT.
The one-sentence idea: a tiny GPT is the same machine as a frontier model at small scale, and you only understand it when you can trace the text through the tokenizer, the attention maths, the optimiser and the PyTorch loop, and name the line that breaks when one of them goes wrong.
The case
Dana, a backend engineer, wants to know what actually happens inside a language model. She follows Andrej Karpathy's "Let's build GPT" approach: a character-level model trained on about 1.1 million characters of Shakespeare. The settings are small enough to run on one GPU in minutes: 4 blocks, 4 heads, a width of 128, a context of 64 characters and a vocabulary of 65 symbols. She uses an AI assistant to write most of the code. Her job is to understand every line well enough to catch what the assistant gets wrong.
Why this matters
AI assistants write plausible PyTorch fast. They also leak the future into attention, forget to clear gradients, leave dropout on during evaluation and quietly "fix" a shape error by throwing away data. None of these crash loudly. Each shows up only as a strange loss number or odd samples. If you cannot read the loss log and the tensor shapes, you cannot tell good output from confident nonsense.
How to do it
- Tokenize and batch. Turn text into integer ids. A character vocabulary is easy to hand-check. A BPE vocabulary, built by repeatedly merging the most frequent adjacent pair, gives shorter sequences but a larger embedding table. Each batch row holds a block of ids, and its target is the same block shifted one position to the right.
- Attend. Each token makes a query, a key and a value. Scores are query-key dot products, divided by the square root of the head size, with future positions set to minus infinity, then softmaxed and used to mix the values. Check by printing one weight matrix: everything above the diagonal must be zero.
- Assemble. Add token and position embeddings, stack blocks (layer norm, attention, residual add, layer norm, MLP, residual add), then project to vocabulary logits. Count the weights: each block here holds about 197,000, so the model is roughly 0.8 million parameters.
- Train. Flatten logits to (BT, C) and targets to (BT) and use cross-entropy. A random start should give a loss near ln(65), about 4.17. Use AdamW at a rate around 1e-3 with a short warmup. Each step runs zero_grad, forward, backward and step.
- Read the curves. Training loss falls almost forever. The held-out loss tells the truth. When it turns up while training loss keeps falling, the model is memorising and you stop, regularise or add data.
- Sample. Generation feeds the last 64 characters, takes the logits at the final position, divides by a temperature and draws the next character. Low temperature repeats. High temperature drifts into noise.
Before and after
A weak check: "the loss went down, so it works". A strong check: the first loss is near ln(65), validation loss is tracked on held-out text, one attention matrix has zeros above the diagonal, and a 200-character sample reads like the corpus.
What goes wrong
- Leaking the future. Without the causal mask, training loss collapses and samples are gibberish.
- Silent training bugs. Missing zero_grad makes gradients accumulate. Missing eval mode makes validation noisy. A shape patch that slices targets trains on one position per block.
- Overclaiming. Fluent samples from 1.1 million characters show style, not understanding. The gap to a chat assistant is data, compute and post-training, not only more epochs.
The AI's role
Use the assistant to draft boilerplate and to explain a stack trace. Never accept a patch for a shape, loss or mask problem without writing down the shape of every tensor before and after, and without a number or a plot that proves the fix.
Steps
Build the batches
Encode the corpus into ids, hold out the last 10% for validation, and write get_batch so each target row is the input shifted by one. Print one x and y pair and check by eye.
Batch function data.py
def get_batch(split): data = train_data if split == 'train' else val_data ix = torch.randint(len(data) - block_size, (batch_size,)) x = torch.stack([data[i:i+block_size] for i in ix]) y = torch.stack([data[i+1:i+block_size+1] for i in ix]) return x, yChoose or train a tokenizer
Start with characters (65 symbols). To try BPE, run a few hundred merges and compare tokens per corpus and embedding table size before deciding. A new tokenizer means retraining the model.
Vocabulary options Corpus 1.1M characters; n_embd = 128; model body about 0.8M weights Vocabulary Tokens in corpus (approx.) Embedding table (weights) 65 (characters) 1,100,000 8,320 512 (BPE) 450,000 65,536 50,000 (BPE) 260,000 6,400,000 Write and check attention
Implement scaled, masked self-attention. Scale by the square root of the head size, set future scores to minus infinity, and print one weight matrix to check the zeros above the diagonal.
Assemble the blocks
Stack embeddings, residual blocks with layer norm and an MLP with a GELU, then a vocabulary projection. Count weights per part. Residual adds and layer norm are what keep the stack trainable.
Choose the optimiser and read the curves
Use AdamW near 1e-3 with a short warmup. Compare train and validation loss over time. Stop near the best validation point if the gap widens.
Run log, 4-layer model, 1.1M characters train.log
step 0: train 4.19 val 4.20step 500: train 1.95 val 2.01step 1000: train 1.52 val 1.61step 2000: train 1.10 val 1.58step 3000: train 0.62 val 1.83step 4000: train 0.31 val 2.24step 5000: train 0.14 val 2.71Write the PyTorch loop
Per step: zero_grad, forward, backward, step. For evaluation use model.eval() and torch.no_grad(), then return to train mode. When the assistant patches a shape error, check the patch kept all B*T positions.
Skills this scenario uses
Where to study
- Neural Networks: Zero to Hero (Andrej Karpathy) (opens in a new tab)CourseFree
The video series this scenario follows, from gradients to a GPT.
- Andrej Karpathy: Let's build GPT from scratch, in code, spelled out (opens in a new tab)VideoFree
A line-by-line build of a character-level GPT on Shakespeare.
- nanoGPT (Karpathy) (opens in a new tab)ToolFree
A compact reference implementation to compare your code against.
- Andrej Karpathy: minbpe and the GPT tokenizer lecture (opens in a new tab)ToolFree
Readable BPE training and encoding code.
- Attention Is All You Need (Vaswani et al., 2017) (opens in a new tab)PaperFree
The paper that defined the scaled dot-product attention used here.
- Adam: A Method for Stochastic Optimization (opens in a new tab)PaperFree
Why Adam keeps two extra values per weight.
- Learn the Basics (PyTorch tutorials) (opens in a new tab)DocsFree
Tensors, autograd and the training loop in the framework's own words.
- The Illustrated Transformer (Jay Alammar) (opens in a new tab)ArticleFree
A picture-first walk through attention and the block.