Module 20
Foundation Models and Large Language Models
How can large-scale training turn a neural architecture into a general model with new capabilities?
- lessons
- 26
- duration
- 45 h 30 min
- concepts
- 155
- available in English
- 26 / 26
- completed by you
0 of 26
Where it fits
Overview
Work through the full LLM pipeline using a local GPU. Start with tokenization, including byte-level BPE from scratch, Unigram and SentencePiece. Study pretraining objectives, pretrain a small model, build a filtered and deduplicated corpus, and investigate scaling laws, compute-optimal training, data mixtures, and emergent capabilities. Then study post-training with SFT, LoRA, QLoRA, reward models, PPO-based RLHF, DPO and its variants, RL with verifiable rewards, RLAIF, distillation, and continual learning. Finish with rigorous evaluation using your own harness, model judges, arenas, and contamination checks. The labs fit in 8 GB of VRAM with models of tens of millions of parameters or LoRA and QLoRA on open models of 0.5 to 3 billion parameters.
Why it matters
This module turns the GPT from Module 18 into a useful LLM and develops the skills required to build and evaluate your own. Diagnose tokenization, allocate parameters and training tokens under a budget, curate data, adapt a model with LoRA, align it with preferences or verifiable rewards, and design reliable evaluations. Use those skills to read open-model technical reports critically and reproduce experiments at a small scale. They also support the agent, inference systems, and model risk modules.
Lessons 26
- 01Review and roadmap: from language model to foundation modelReview autoregressive factorization, per-token cross-entropy, perplexity, bits per byte, and the decoder-only GPT from module 18. Define a foundation model and map the full lifecycle of a modern LLM.
- 02Text as bytes: Unicode, UTF-8 and the vocabulary problemStudy Unicode code points, UTF-8, and normalization before comparing tokenization units by coverage, vocabulary size, sequence length, and computational cost.
- 03Byte Pair Encoding from scratchBuild a complete byte-level BPE tokenizer, including pretokenization, merge training, rank-based encoding and decoding, and special-token handling. Accelerate training and compare its output with existing tokenizers.
- 04WordPiece, Unigram, SentencePiece and tokenization pathologiesStudy WordPiece, Unigram, SentencePiece, and subword regularization, then examine numerical tokenization, language disparities, under-trained tokens, vocabulary extension, and byte-based models.
- 05Next-token prediction: the causal objective at scaleFormalize causal pretraining as maximum likelihood and implement shifted labels, loss masks, document boundaries, and correct token normalization under gradient accumulation. Analyze loss, exposure bias, planning, and multi-token prediction.
- 06Bidirectional and denoising objectives: MLM, span corruption and FIMStudy BERT masked language modeling, pseudo-log-likelihood, T5 span corruption, UL2 denoisers, ELECTRA, and fill-in-the-middle. Compare a mini BERT and mini GPT with probes and generation under a comparable budget.
- 07Pretraining a small LLM end to endBuild a reproducible pretraining pipeline using binary token shards and memory-mapped windows, set a token budget, train with a WSD schedule, monitor domain losses, and resume checkpoints.
- 08Evaluating a base model: perplexity, benchmarks and your own harnessEvaluate base models with sliding-window perplexity, multiple-choice likelihood, generative extraction, pass@k, prompt sensitivity, and confidence intervals, and compare a custom harness with a reference.
- 09Building a pretraining corpus: extraction and filteringStudy web-text extraction, language identification, heuristic and model-based quality filters, privacy and toxicity filtering, controlled data ablations, and corpus documentation.
- 10Deduplication at scale: hashing, MinHash and LSHStudy exact, substring, near-exact, and semantic deduplication, derive MinHash and banded LSH, group verified pairs, and examine the measured effects of repeated data.
- 11Scaling lawsStudy empirical scaling laws for parameters, data, and compute; account for transformer FLOPs; fit robust power laws with uncertainty; and evaluate a held-out extrapolation.
- 12Compute-optimal training: Chinchilla and beyondDerive compute-optimal parameter and token allocation, compare Chinchilla estimation approaches, and study inference-aware, data-constrained, and hyperparameter scaling.
- 13Data mixtures and synthetic dataStudy domain mixtures, DoReMi, mixing laws and RegMix, synthetic pretraining data, web rephrasing, and recursive model collapse.
- 14Emergent abilities and in-context learningStudy emergent abilities, metric-induced thresholds, capability prediction, and in-context learning, including sensitivity to examples and labels, data structure, and theoretical explanations.
- 15Instruction tuning and supervised fine-tuningStudy instruction-response supervised fine-tuning, curated and synthetic datasets, chat templates, assistant-only loss, packing, and instruction-following evaluation.
- 16Parameter-efficient fine-tuning and LoRA from scratchAccount for full fine-tuning memory, compare PEFT families, derive low-rank LoRA updates, and implement, merge, and compare adapters with PEFT.
- 17QLoRA and fine-tuning in 8 GBStudy QLoRA's NF4 quantization, double quantization, and paged optimizers, then compare LoRA rank, scaling, learning rates, variants, and retention.
- 18Human preferences and reward modelsStudy pairwise preferences, Bradley-Terry and Plackett-Luce, reward models, their evaluation, and the KL cost of best-of-N selection.
- 19RLHF with PPODerive token-level RLHF and study PPO, GAE, KL control, reward overoptimization, and practical evaluation.
- 20Direct Preference OptimizationDerive DPO from KL-regularized RLHF and study its gradients, sequence likelihoods, training, evaluation and limitations.
- 21Beyond DPO: IPO, KTO, SimPO, ORPO and iterative optimizationCompare preference optimization objectives and design controlled evaluations, including iterative online DPO.
- 22Critic-free RL for LLMs: REINFORCE, RLOO and GRPOStudy sequence policy gradients, RLOO, GRPO, normalization and verifiable rewards.
- 23RLAIF and Constitutional AIStudy AI-labeled preferences, Constitutional AI, judge prompting and biases, and compare local-model labels with human judgments.
- 24Distilling LLMsStudy black-box, sequence, token-logit, on-policy and verified reasoning-trace distillation for language models.
- 25Continual learning, catastrophic forgetting and model mergingMeasure forgetting and study continual pretraining, replay, EWC, alignment tax and model merging.
- 26Evaluating LLMs II: judges, arenas and contaminationEvaluate assistants with model judges, length-controlled wins, arena ratings and benchmark-contamination tests.
Module capstone
Build your own LLM end to end in 8 GB
Create one reproducible report covering two parts. First, train your own BPE tokenizer on a corpus curated by the module's filtering and deduplication pipeline. Choose the model size and token count with a scaling sweep, then pretrain a model of about 50 million parameters with WSD and cooldown. Evaluate it with your own harness and a contamination check. Second, use QLoRA to adapt an open 1.5 to 3 billion parameter model into a technical assistant using public data, such as CWE descriptions and OWASP guidance for application security. Align it with DPO using preferences from a local judge that controls position and length bias, then apply GRPO to a subtask with a verifiable reward. Deliver three-seed ablations with confidence intervals, a forgetting matrix for general capabilities, judge validation against a manually labeled sample, and model and dataset cards.
Check what you already know
- Convert nats per token to bits per byte and explain why the result can compare tokenizers
- Encode Unicode code points in UTF-8 by hand and calculate tokenizer fertility across languages
- Implement byte-level BPE training and rank-based encoding with regex pretokenization
- Segment with Viterbi in a Unigram tokenizer and diagnose failures in number tokenization
- Implement masked causal loss with normalization under gradient accumulation
- Build training data for 80/10/10 masked language modeling, span corruption, and fill-in-the-middle
- Plan and run pretraining with a memory-mapped loader and a WSD schedule
- Implement multiple-choice evaluation by log-likelihood with normalization and the unbiased pass@k estimator
- Design heuristic and model-based filters for a web corpus and validate them through ablations
- Derive the LSH S-curve and choose bands and rows for a Jaccard similarity threshold
- Fit a scaling law L(N, D) with Huber loss in log space and quantify its uncertainty
- Derive a compute-optimal allocation and explain when it pays to train a small model on more tokens
- Explain DoReMi and model collapse from training with synthetic data
- Distinguish an emergent capability from a metric artifact
- Build a chat template that applies the loss only to assistant turns
- Implement LoRA from scratch, merge the weights, and count trainable parameters
- Build NF4 from normal quantiles and calculate QLoRA fine-tuning memory
- Derive Bradley-Terry from utilities with Gumbel noise and train a reward model
- Implement PPO for an LLM with a per-token KL penalty and generalized advantage estimation
- Derive the DPO loss from the KL-regularized RLHF objective
- Place IPO, KTO, and SimPO within the ΨPO framework
- Calculate RLOO and GRPO advantages and explain the bias introduced by length normalization
- Design LLM-based preference labeling with a control for position bias
- Choose among black-box, logit, and on-policy distillation for a scenario
- Derive EWC and merge models with task arithmetic and TIES
- Estimate arena Bradley-Terry ratings with bootstrap and detect benchmark contamination