Build an LLM From Scratch
For engineers who want to understand a language model down to the matrix multiply.
No black boxes. Start at raw bytes and end at an aligned assistant — tokenization, embeddings, attention, the full forward pass, the training loss, and RLHF — each idea paired with a runnable challenge or lab that makes you build the piece by hand.
- Explain every stage from tokens to a trained, aligned model
- Implement attention, softmax, layer-norm and cross-entropy by hand
- Reason about scaling laws and why pretraining works
- Understand how RLHF turns a raw LM into an assistant
- LabNext up
The Tokenizer
Text becomes tokens: watch BPE build a vocabulary from raw bytes.
- Challenge
BPE Merge Step
Implement the merge step every BPE tokenizer is built on.
- Handbook
The Embeddings Handbook
Tokens become vectors — what an embedding actually is.
- Paper Breakdown
Word2Vec
The paper that made “king − man + woman ≈ queen” real.
- Lab
The Meaning Map: Embeddings
Fly through an embedding space and see meaning as geometry.
- Paper Breakdown
Seq2Seq
Before attention: encoder→decoder and its bottleneck.
- Paper Breakdown
Attention Is All You Need
The Transformer — the architecture every LLM inherits.
- Challenge
Single-Head Attention
Implement scaled dot-product attention from scratch.
- Lab
The Spotlight: Attention
Watch attention weights light up token to token.
- Challenge
Softmax
The function at every attention and output head.
- Challenge
Layer Normalization
The normalization that keeps deep stacks trainable.
- Lab
Inside a Transformer: Self-Attention
Push a sequence through a full forward pass, layer by layer.
- Handbook
The Transformers Handbook
Consolidate: the whole architecture in one handbook.
- Paper Breakdown
RoPE (RoFormer)
How modern models encode position — rotary embeddings.
- Paper Breakdown
GPT-3
Scale it up: few-shot learning emerges.
- Paper Breakdown
Scaling Laws
Why more parameters and data predictably help.
- Challenge
Cross-Entropy Loss
The loss you train a language model against.
- Handbook
The Fine-Tuning Handbook
Adapt a pretrained model to your task.
- Paper Breakdown
InstructGPT
Turn a raw LM into an assistant — RLHF.
- Lab
The Taste Trainer: RLHF & DPO
Practice the preference-tuning loop by hand.
How this path works
This path is for engineers who use language models every day and want to know what happens between the prompt and the next token: application developers tired of treating the model as a black box, ML engineers coming from vision or tabular work, and anyone preparing for interviews that ask how a Transformer is built. You need comfortable Python and some ease with vectors and logarithms.
Understanding a model at this level means you can trace one token's journey. Byte-pair encoding turns text into token IDs, each ID becomes an embedding vector, attention mixes information between positions through queries, keys and values, softmax and layer normalization keep the numbers well behaved, and cross-entropy measures how surprised the model was by the true next token. Scaling laws explain why bigger models trained on more data improve predictably, and preference training explains how a raw predictor becomes an assistant.
The steps follow the data through the model. Tokenization comes first because everything downstream sees integers, not letters, and embeddings come next, with word2vec as their origin. Seq2seq shows the bottleneck attention removed, then the Transformer paper, your own attention code and two labs make the mechanism concrete. Softmax and layer norm are the small parts inside each block, the Transformers Handbook assembles them, RoPE handles position, and the last stretch moves from scale and loss to fine-tuning and RLHF.
What each step gives you
The Tokenizer
Type anything and watch it split into sub-word tokens with integer IDs, race character, word and sub-word tokenizers, then build byte-pair encoding by merging the most frequent pair on a tiny corpus. It answers the first question of the path, what the model actually reads, and explains practical effects such as token cost, context limits and why models miscount the letters in strawberry.
BPE Merge Step
Implement one BPE training step: count every adjacent symbol pair across the corpus, pick the most frequent with a lexicographic tie-break, and merge every non-overlapping occurrence from left to right. Repeat that step a few thousand times and you have trained a tokenizer, which prepares you to discuss vocabulary-size trade-offs and why the same word can split differently in different models.
The Embeddings Handbook
Tokens become vectors arranged so that similar meaning lands nearby, and this handbook covers why the angle between vectors is the similarity, why you normalize and then take a dot product, what extra dimensions buy, and the pitfalls of embeddings in real search systems. It gives you the vocabulary for the embedding lookup at the bottom of every Transformer and for the cosine questions that follow.
Word2Vec
The 2013 paper that learned dense word vectors from the company words keep, through skip-gram and CBOW, and made king minus man plus woman landing near queen famous. The breakdown is candid that the analogy arithmetic works less cleanly than the famous examples suggest, and its core limit, one vector per word whatever the context, is the gap later contextual models were built to close.
The Meaning Map: Embeddings
Click through a map of twelve words where royalty, animals and places cluster, rank each word's nearest neighbors by cosine, and run analogies such as king minus man plus woman or Paris minus France plus Japan. It turns the previous two steps into geometry you can see, which helps when you need to explain why cosine ignores vector length and how concepts become directions.
Seq2Seq
The 2014 encoder-decoder paper that replaced a translation pipeline with one network, and its weakness: the whole input squeezed into a single fixed-length vector. Knowing that bottleneck makes attention feel necessary rather than arbitrary, and the paper's reversed-input trick and its case for beam search over greedy decoding still come up in questions about generation.
Attention Is All You Need
With the bottleneck in mind, the 2017 paper replaces recurrence with self-attention: queries, keys and values, the scaled dot-product formula computed by hand, multi-head attention, positional encoding and the full encoder-decoder architecture. Read it as the blueprint for every later step in this path, and run its 30-line Python self-attention so the next challenge is a translation exercise rather than a puzzle.
Single-Head Attention
Write scaled dot-product attention yourself: score each query row against every key, divide by the square root of d, softmax each row into weights, and return the weighted sum of the value rows. Passing the hidden tests prepares you for whiteboard requests to implement attention in NumPy and for the question of why the scaling factor is there at all.
The Spotlight: Attention
Click any word in a short sentence and see how its attention splits across the others, with a verb leaning on its subject and a determiner pointing at its noun, as weights that sum to one. Use it right after writing attention to connect your score matrix to what heads are said to learn, remembering that the page's numbers are a hand-picked illustration rather than output from a trained model.
Softmax
Softmax runs inside every attention head and once more at the output, where it turns logits into a next-token distribution, so here you write the stable version that subtracts the maximum before exponentiating. Once it passes, connect it back to the model: dividing logits by a temperature before this function is exactly how sampling becomes sharper or flatter.
Layer Normalization
Implement layer normalization for one vector: subtract the mean, divide by the square root of the variance plus an epsilon, then apply a learned per-element scale and shift. It is the stabilizer wrapped around every Transformer sub-layer, and writing it prepares you for questions about why deep stacks need normalization, what the epsilon protects against, and how layer norm differs from batch norm.
Inside a Transformer: Self-Attention
Pick a query token in the four-token sentence The robot picked it and step through the arithmetic: scores from query-key dot products scaled by the square root of d, softmax weights, and the context vector as a weighted sum of values. Watching it attend most to robot with real numbers is a check that your challenge code and your mental model agree.
The Transformers Handbook
The consolidation step: tokens, embeddings and position, self-attention and multi-head attention, then the transformer block itself, with its feed-forward network, residual connections and layer normalization, a block's parameter budget and what has changed since 2017, and how a stack of blocks produces text. After the pieces you have built, this is where they assemble into one forward pass you should be able to draw and narrate end to end.
RoPE (RoFormer)
Attention is order-blind, and RoPE's answer is to rotate queries and keys by an angle that depends on position, so their dot product depends only on the distance between tokens. The breakdown compares absolute and relative schemes, shows relative position falling out of the rotation, and covers frequencies and long context, the background for questions about how LLaMA-style models handle position.
GPT-3
Scaling a decoder-only Transformer to 175 billion parameters made few-shot, in-context learning appear without any fine-tuning, and this breakdown derives the 175B figure by hand and lets you size and price any GPT on a napkin. It prepares you to explain zero-, one- and few-shot prompting, how GPT-3 differs from BERT, and the limitations its authors admitted.
Scaling Laws
Kaplan and colleagues showed loss falling as a smooth power law in parameters, data and compute, which turned model sizing into a forecast. The page works the laws with real numbers, explains how to spend a fixed compute budget, and covers how Chinchilla later revised the recommended balance toward more data, so you can explain both why pretraining keeps paying off and where the original advice changed.
Cross-Entropy Loss
Implement the loss a language model trains against: the negative log-probability assigned to the true class, for either an index or a one-hot target, with an epsilon guard so a zero probability gives a large finite loss instead of infinity. It connects softmax to training and prepares you to explain perplexity, label smoothing, and why the loss punishes confident mistakes so heavily.
The Fine-Tuning Handbook
With a pretrained model in hand, this handbook covers how to adapt it: when to fine-tune instead of prompting or retrieval, full fine-tuning versus parameter-efficient methods, how a LoRA update works and how few parameters it really trains, data quality, catastrophic forgetting and evaluation. It prepares you to size a LoRA run yourself and to defend that choice in a design discussion.
InstructGPT
InstructGPT's three steps, supervised fine-tuning, a reward model trained on human rankings, and reinforcement learning with PPO, are how a raw next-token predictor became an assistant that follows instructions. The breakdown includes training a reward model from preferences and the result that a much smaller aligned model was preferred over GPT-3, which sits at the center of any question about what RLHF changes.
The Taste Trainer: RLHF & DPO
You play the labeler, picking the better of two answers until a reward model predicts your taste, then turn up the optimization pressure and watch the policy hack the reward while a KL penalty pulls it back. The final act compares the classic pipeline with DPO, which trains directly on preference pairs, so you can explain why DPO became a common default for preference tuning.
A study plan
- Week 1
Tokens and vectors: The Tokenizer lab, the BPE merge challenge, The Embeddings Handbook, the word2vec breakdown and The Meaning Map. Run your merge function by hand on a three-word corpus and check it against the lab. End the week able to explain, without notes, how a sentence becomes a list of vectors.
- Week 2
Attention: the seq2seq and Attention Is All You Need breakdowns, the single-head attention challenge, and both attention labs. At the end of the week, rewrite attention from a blank file, then compute one row of scores by hand on a three-token example to confirm the numbers in your head match the code.
- Week 3
Inside the block: softmax, layer norm, The Transformers Handbook and RoPE. Draw one transformer block from memory with every tensor shape labeled, then check it against the handbook. As an extra exercise outside the path, wire your attention, softmax and layer norm functions into a single block in NumPy.
- Week 4
Scale and alignment: GPT-3, scaling laws, cross-entropy, fine-tuning, InstructGPT and the Taste Trainer lab. Use the napkin sizing from the GPT-3 breakdown to estimate the parameter count of a model you use, and write a one-paragraph explanation of the three InstructGPT steps for a colleague.
Questions about this path
Can you build a large language model from scratch on your own?
You can build a small one. A Transformer with a few million parameters trained on a modest text corpus runs on a laptop or a single consumer GPU, and building one is a reliable way to make every piece concrete. Models with billions of parameters need large clusters and data pipelines far beyond an individual budget, so from scratch in practice means writing the architecture and training it yourself at small scale. This path gives you the pieces; wiring them into a training run is the natural next project.
What math do I need to understand Transformers?
Less than people expect. You need vectors and dot products for embeddings and attention, matrix multiplication to see attention as one operation over a whole sequence, exponentials and logarithms for softmax and cross-entropy, and the idea of a derivative to follow training. An introductory linear algebra course is plenty for this path, with no measure theory or advanced statistics required. Each challenge implements one formula in a few lines of Python, which is often the fastest way to make the math stick.
How long does it take to understand how an LLM works?
With solid programming skills, a focused month of evenings is enough to understand the whole pipeline: tokenization, embeddings, attention, the transformer block, the training loss, scaling and alignment. Reading and coding through this path takes a few weekends; the slower part is returning to attention until you can derive it on a whiteboard without notes. Training a small model of your own afterward usually takes another week or two of experimenting.
What is the difference between pretraining and fine-tuning?
Pretraining teaches a model general language ability by predicting the next token across a huge text corpus while minimizing cross-entropy loss, and it is where almost all the compute goes. Fine-tuning starts from those weights and adjusts them on a much smaller, targeted dataset so the model follows a format, a domain or instructions. Parameter-efficient methods such as LoRA train small low-rank updates instead of every weight, and preference tuning with RLHF or DPO is a further stage that optimizes for answers people judge to be better.
Is RLHF still used, or has DPO replaced it?
Both are used. DPO became a common default for preference tuning because it trains directly on pairs of preferred and rejected answers with a simple loss and no separate reward model or reinforcement-learning loop, which makes it cheaper and more stable. Classic RLHF remains useful when you want an explicit, reusable reward model or online training against fresh samples. Many training pipelines combine supervised fine-tuning with one or more preference stages, and the Taste Trainer lab lets you compare the two side by side.
The best way to truly understand a language model is to build one. This path goes down to the matrix multiply — tokens, embeddings, attention, the training loss — so the model stops being a black box and becomes a system you can reason about, debug, and extend with confidence.