Phase 7 · Transformers/
Lesson 7.8core6 h

Build GPT from scratch (nanoGPT walkthrough)

From a bigram table to a Shakespeare generator — then to GPT-2 124M

Nothing makes the transformer concrete like typing every line of one and watching the loss fall. Karpathy's walkthrough assembles the components of 7.2 Scaled dot-product and multi-head attention, fully derived–7.6 Decoder-only: GPT and autoregressive generation in order on a tiny dataset, and the same code — scaled by nanoGPT, llm.c and nanochat — reproduces GPT-2. After this project, model configs, training logs and inference loops stop being abstractions, and every later lesson on scaling (7.9 Scaling laws and compute-optimal training), inference (7.10 Efficient inference: KV cache, GQA, FlashAttention, speculative decoding, quantization) and fine-tuning (8.2 Fine-tuning and PEFT) has a model you own to try things on.

You'll be able to

  • Implement a character-level GPT (tokenizer, causal self-attention, blocks, embeddings, head) in PyTorch
  • Train it with AdamW, read the loss curves and samples, and diagnose overfitting
  • Extend the model with a KV cache, RoPE or your own dataset
  • Read nanoGPT's and llm.c's code and understand what changes to reach GPT-2 124M

Key ideas

  1. A GPT is embeddings + L pre-norm blocks (causal self-attention and an MLP with residuals) + a final LayerNorm and an unembedding head.
  2. Initial loss should equal ln(vocab size); a bigram table reaches ≈2.5 on Tiny Shakespeare, the 10M-parameter GPT reaches ≈1.48.
  3. One training window of block_size tokens provides block_size next-token predictions thanks to the causal mask.
Show 3 more key ideas
  1. Small data and a big model overfit quickly — dropout, weight decay and early stopping matter here even though frontier models skip them.
  2. nanoGPT, llm.c and nanochat are the same model at GPT-2 scale with a BPE tokenizer, weight tying and tuned hyperparameters.
  3. Reproducing GPT-2 124M on 10B tokens is now a weekend project on rented GPUs.

Suggested path through this lesson