Build an LLM from Scratch
Build a small GPT-style language model yourself in Python: tokenizer, attention, training, fine-tuning and serving.
You will learn to
- Write a tokenizer, a transformer and a training loop in plain Python and PyTorch
- Explain attention, embeddings and the loss, with numbers you checked
- Train a small model on your own data and sample text from it
- Fine-tune, align, evaluate and serve a model, and know what changes at scale
Module 1: The big picture and the tools
- Lesson 1.1: What a language model is, and what we will build
- Lesson 1.2: Setting up Python, NumPy and a tiny dataset
- Lesson 1.3: Tensors, gradients and autograd by hand
- Lesson 1.4: A first model: the bigram language model
Module 2: Text to numbers
- Lesson 2.1: Tokenisation: characters, words and subwords
- Lesson 2.2: Byte-pair encoding from scratch
- Lesson 2.3: Embeddings, vectors and token positions
- Lesson 2.4: Context windows, batches and the data loader
Module 3: Attention
- Lesson 3.1: Why averaging the past is not enough
- Lesson 3.2: Self-attention: queries, keys and values
- Lesson 3.3: Causal masking and multi-head attention
- Lesson 3.4: Scaling attention: cost, memory and KV caches
Module 4: The transformer block
- Lesson 4.1: Residual connections and layer normalisation
- Lesson 4.2: The feed-forward network and activations
- Lesson 4.3: Assembling a GPT from blocks, norms and an output layer
- Lesson 4.4: Initialisation, parameter counts and shapes
Module 5: Training
- Lesson 5.1: The loss: cross-entropy and perplexity
- Lesson 5.2: Optimisers: SGD, Adam and weight decay
- Lesson 5.3: Learning-rate schedules, batch size and gradient clipping
- Lesson 5.4: Training a small model end to end and reading the curves
Module 6: Generation
- Lesson 6.1: Sampling: greedy, temperature, top-k and top-p
- Lesson 6.2: Beam search and its limits
- Lesson 6.3: Evaluating a language model
- Lesson 6.4: Scaling laws and what changes at large scale
Module 7: From base model to assistant
- Lesson 7.1: Fine-tuning on instructions
- Lesson 7.2: Parameter-efficient tuning with LoRA
- Lesson 7.3: Preference tuning: reward models, RLHF and DPO
- Lesson 7.4: Safety, refusals and alignment limits
Module 8: Smaller models from larger ones
- Lesson 8.1: Knowledge distillation: soft targets and temperature
- Lesson 8.2: Distilling a language model: logits, KL loss and a worked example
- Lesson 8.3: Synthetic data and sequence-level distillation from a teacher
- Lesson 8.4: Pruning, shrinking and when distillation fails
Module 9: Serving and next steps
- Lesson 9.1: Quantisation and making models small
- Lesson 9.2: Inference: batching, KV caches and speculative decoding
- Lesson 9.3: Capstone: train, evaluate and serve your own model
- Lesson 9.4: Where to go next: mixture of experts, long context and open models