Language Models from Scratch
Building Language Models from Scratch: Course Notes
📚 Course Philosophy and Motivation
Modern AI research suffers from a growing disconnect: researchers increasingly interact with language models only through prompting APIs rather than building or fine-tuning models themselves. While abstraction layers (like calling GPT-4) unlock productivity, they are leaky abstractions — the underlying technology remains poorly understood. Fundamental research often requires tearing up the stack and co-designing data, systems, and models.
The core philosophy: To understand it, you must build it.
Frontier models (e.g., GPT-4 with estimated 1.8 trillion parameters, 100M training cost) are out of reach for academic settings and have no public details. Therefore, this course focuses on small language models, with the caveat that some behaviors (e.g., emergent abilities like in-context learning) may not appear at small scale. The plot below from Wei et al. (2022) shows that accuracy on many tasks remains flat until a certain compute threshold, then suddenly rises — a phenomenon absent at small scale.
Three types of knowledge the course imparts:
Mechanics: how transformers, tokenizers, parallelism work — fully teachable.
Mindset: squeezing maximum performance from hardware and taking scaling seriously — can be instilled.
Intuitions: which data and modeling decisions work at large scales — only partially teachable, because small-scale results may not transfer.
The Bitter Lesson Reinterpreted
The bitter lesson is often misread as "scale alone matters." The correct interpretation is that algorithms at scale matter. Accuracy is a product of efficiency and resources. At large scale, efficiency becomes even more critical: spending hundreds of millions of dollars forces extreme optimization. For example, algorithmic efficiency improvements from 2012 to 2019 gave a 44× reduction in compute needed to train ImageNet to a given accuracy — faster than Moore's law.
The right mindset: What is the best model one can build given a certain compute and data budget? This question applies at every scale, from a single GPU to a datacenter.
🔬 The Current Landscape & Historical Context
Language modeling has a long pre-deep-learning history:
Shannon used language models to estimate entropy of English.
Google trained 5-gram models on 2 trillion tokens as early as 2007 (more tokens than GPT-3).
These n-gram models lacked the emergent phenomena of modern neural LMs.
Key milestones in the deep learning era:
2003: First neural language model (Bengio) — learned distributed representations.
Seq2seq models (Ilya Sutskever, Google) enabled sequence modeling.
Adam optimizer (2014) — still dominant for most training.
Attention mechanism developed for machine translation.
Transformer (Vaswani et al., 2017) — "Attention Is All You Need."
Mixture of Experts and model parallelism research in late 2010s enabled 100B+ parameter models.
The shift to foundation models: ELMo, BERT, T5 showed that pre-training on large text corpora followed by fine-tuning could work for many tasks. OpenAI then combined these ingredients with scaling law mindset, engineering, and capital to produce GPT-2, GPT-3. This launched the current era of frontier models (GPT-4, Claude, Gemini, LLaMA, DeepSeek, etc.).
Levels of openness:
Closed models: weights and details undisclosed (e.g., GPT-4).
Open-weight models: weights released but data often hidden (e.g., LLaMA).
Open-source models: weights, data, and detailed paper available (e.g., some models from AI2, DeepSeek).
Current frontier labs compete at massive scale (e.g., xAI building clusters with 200,000 H100s). The course revisits the classic ingredients and traces how they evolved into modern best practices, using information from the open community and reading between the lines of closed models.
📋 Course Overview: Five Pillars
The entire course is driven by efficiency — given hardware and data, how to train the best model. Organizing questions: given a common crawl dump and 32 H100s for two weeks, what should you do? Design decisions span tokenizer, architecture, systems, data, alignment.
Pillar | Focus | Assignment |
|---|---|---|
Basics | End-to-end pipeline: tokenizer, transformer, training loop | Build BPE tokenizer, transformer with cross-entropy loss, AdamW optimizer. Leaderboard on OpenWebText perplexity (90 min on H100). |
Systems | Hardware optimization: kernels, parallelism, inference | Write GPU kernels (Triton), implement data parallelism and simplified model parallelism. Benchmark and profile. |
Scaling Laws | Optimal model size and data for given compute | Use a training API to explore hyperparameters, fit scaling law, predict best configuration at larger scale. |
Data | Data curation: acquisition, extraction, filtering, deduplication | Process raw Common Crawl dump, train classifiers, deduplicate. Leaderboard on perplexity given token budget. |
Alignment | Making models useful: instruction following, safety | Implement supervised fine-tuning (SFT), DPO, and GRPO. |
Basics: Tokenizer, Architecture, Training
Tokenization converts strings to integer sequences (tokens). The course uses Byte Pair Encoding (BPE) — a simple yet effective heuristic from 1994. (See detailed section below.)
Model architecture: Starting point is the original transformer (2017). Many improvements since then, each making a substantial difference:
Activation function: SwiGLU (introduced in 2020 — "no explanation except divine benevolence").
Positional embeddings: Rotary Position Embeddings (RoPE).
Normalization: Root Mean Square Layer Normalization (RMSNorm) is simpler than LayerNorm; placement of normalization changed.
MLP: Dense or Mixture of Experts (MoE).
Attention: full attention, sliding window, linear attention; low-rank variants (GQA, MLA).
Beyond transformers: state-space models like Hyena, or hybrid architectures.
Training: AdamW optimizer (Adam with decoupled weight decay). Learning rate schedule, batch size, regularization. Details matter: order-of-magnitude differences between a vanilla transformer and a well-tuned one.
Systems: Kernels, Parallelism, Inference
GPUs are arrays of compute units with off-chip memory (HBM) and on-chip caches (L1, L2). Data movement is the bottleneck — analogous to moving goods from a warehouse to a factory. Techniques like fusion and tiling minimize movement during matrix multiplication.
Two main phases of inference:
Prefill: Process entire prompt in parallel (compute-bound).
Decode: Autoregressive generation one token at a time (memory-bound) — hard to saturate GPUs.
Speedups for inference:
Cheaper models.
Speculative decoding: use a draft model to generate multiple candidate tokens, then verify with the full model in parallel.
Systems optimizations: kernel fusion, KV-cache management.
Scaling Laws
Fundamental question: given a flop budget, what model size and data volume maximize performance? Larger models require fewer tokens; smaller models more tokens. Chinchilla optimal result: for every compute budget, there is an optimal parameter count N. Empirically, the optimal number of training tokens is approximately 20×N. So a 1.4B parameter model should train on about 28B tokens. This rule ignores inference cost — it focuses purely on training efficiency.
Assignment: Given a flop budget, run experiments with different hyperparameters, fit a scaling law curve, and predict the best model size and data amount for a larger scale. No infinite budget — prioritize experiments carefully.
Data
Data is a key differentiator. "Training on the internet" is a fiction; data must be actively acquired and processed. Common Crawl samples show that most web content is spam, low-quality, or non-English. Processing steps:
Crawl from internet.
Convert HTML/PDF to text (lossy).
Filtering: train classifiers to identify high-quality text and remove harmful content.
Deduplication to prevent overfitting and data contamination.
Evaluation metrics: perplexity, standardized tests (MMLU), instruction following (human eval, LLM-as-judge), chain-of-thought reasoning, and system-level evaluation for agentic uses.
Alignment
A base model (trained only for next-token prediction) has raw potential but needs alignment to be useful: instruction following, style control, safety.
Supervised Fine-Tuning (SFT): Train on prompt-response pairs. Even 1,000 examples can suffice if the base model is strong.
Learning from Feedback:
Preference data: Given two responses (A and B), annotator says which is better. Simplified algorithm: Direct Preference Optimization (DPO).
Verifier feedback: For math or code, a formal verifier can score responses. Full RL needed — Group Relative Policy Optimization (GRPO) simplifies PPO by removing the value function (developed by DeepSeek).
Assignment: Implement SFT, DPO, and GRPO; evaluate.
🔤 Tokenization (Byte Pair Encoding, BPE)
Tokenization is the process of converting raw text (Unicode string) into a sequence of integers (tokens). The vocabulary size is the number of distinct token IDs.
Why Not Simpler Approaches?
Approach | Description | Problems |
|---|---|---|
Character-based | Map each Unicode code point to its integer code point. | Huge vocabulary; some characters very rare (inefficient). Compression ratio ~1 byte/token (low). Sequences long → quadratic attention. |
Byte-based | Convert to UTF-8 bytes (0-255) and use each byte as a token. | Compression ratio exactly 1 byte/token → very long sequences. Even worse for attention. |
Word-based | Split by whitespace/punctuation (regex). | Unbounded vocabulary; unknown words get |
BPE: Adaptive Tokenization
BPE was originally a data compression algorithm (Gage, 1994) and introduced to NLP for neural machine translation. GPT-2 popularized it for language modeling. The key insight: train the tokenizer on raw text so common character sequences become single tokens, rare ones stay as multiple tokens.
Algorithm:
Start with byte-level representation of the training corpus (sequence of integers 0–255).
Count frequencies of all adjacent token pairs.
Merge the most frequent pair: assign a new token ID (starting at 256), replace every occurrence of that pair with the new ID.
Repeat until vocabulary reaches desired size.
Encoding: apply the merges in order (from first to last) to convert new text to token IDs.
Decoding: map each token ID to its byte sequence via the vocabulary.
Example (simplified): Text "cat hat". Bytes: [99,97,116,32,104,97,116]. Count pairs: (99,97)=1, (97,116)=2, (116,32)=1, (32,104)=1, (104,97)=1, (97,116)=2. Most frequent: (97,116) — merge to ID 256. Corpus becomes [99,256,32,104,256]. Continue merging.
Properties:
Reversible: no unknown tokens.
Compression ratio > 1: GPT-2 tokenizer gives ~1.6 bytes per token.
Pre-tokenization: For efficiency, GPT-2 first splits text into word-like segments (using regex), then runs BPE within each segment. This is the approach in the assignment.
Special tokens: e.g.,
<|endoftext|>for separating documents.
Implementation challenges: naive encoding loops over all merges each time — inefficient. Assignment requires building a fast BPE tokenizer from scratch, with options for parallelization.
Practical Observations (GPT-2 / GPT-4 tokenizers)
Spaces are part of tokens (by convention, space precedes the token).
"hello" and " hello" are different tokens — can cause subtle problems.
Numbers are split left-to-right (not semantically grouped).
Emojis require multiple bytes (up to 4 bytes per character) → multi-token.
✅ Key Takeaways
Efficiency is the driving principle behind every design decision: tokenization, architecture, training, data processing, alignment.
The course emphasizes building from scratch to gain deep understanding of the full stack — mechanics, mindset, and partial intuitions.
Tokenization (BPE) is a necessary evil for now; future architectures may bypass it by operating directly on bytes.
Scaling laws provide quantitative guidance for resource allocation.
Data curation is as important as model design.
Alignment techniques (SFT, DPO, GRPO) adapt base models for practical use.
Next lecture: Deep dive into PyTorch building blocks and resource accounting — understanding where all the flops go.

Ask anything
We've read this whole study set, so questions about it get the best answers.