Take the unfinished sentence "The capital of France is". You can finish it without thinking, and a large language model (LLM) finishes it in a way that isn't far off: it gives every possible next piece of text a probability, picks one, and "Paris" will almost certainly get the biggest share. Add the chosen piece to the sentence and ask again, and you get a whole paragraph, one piece at a time. Everything a modern assistant does is built on that single move, and this chapter follows our one sentence through the whole machine, from how it's cut into pieces to how the model that completes it gets turned into one that answers questions.
The idea has a short history. Before 2018, each language task had its own architecture, or at least its own fine-tuned copy with a separate output layer, even after pretrained embeddings and BERT-style fine-tuning. GPT (2018) showed that a single decoder-only Transformer, pretrained only to predict the next token (a piece of text, roughly a word), could beat task-specific models. GPT-3 (2020, 175B parameters, meaning 175 billion learned weights) needed no fine-tuning for many tasks, only a few examples written into the prompt. In 2022, InstructGPT showed that supervised fine-tuning followed by reinforcement learning from human feedback (RLHF) turns a pretrained text completer into something that follows instructions, and the Chinchilla paper showed that most large models were undertrained for their size, which changed how labs split their compute between model size and data.
Structurally, an LLM is the decoder half of the 2017 Transformer, stacked deep, with one tweak called causal masking, and its training objective is to predict the next token. Do that at the scale of the internet and the model ends up knowing grammar, facts and a surprising amount of reasoning. What you get is still a text completer and falls short of an assistant, so two more stages follow. Supervised fine-tuning (SFT) teaches the model to answer in the right format, and preference optimization, in the form of RLHF or DPO, teaches it which of several plausible answers people prefer. In short, an LLM is next-token prediction, scaled up and then aligned.
You've met attention and the Transformer block in chapter 08, and the history of pretraining in chapter 09. We'll define each term again when we use it. First we'll look at why predicting the next token is a useful thing to train on, then at how text becomes the numbers the model reads, then at the stack that reads them and the loss that trains it. After that we'll see how much model and data a training budget should buy, how the finished completer becomes an assistant, and what it costs to adapt and run something that size.
01Predicting the next token
Suppose we want a program that can continue text, and we want to train it with examples. Ordinary supervised learning needs pairs of an input and the right answer, and getting people to write those pairs is slow and expensive. Look at "The capital of France is" again, though. Somewhere in a book or a web page that sentence continued with a word, and the author already wrote it. Cut any text at any point and you have an example for free: everything before the cut is the input, and the piece of text right after it is the answer. That piece is called a token (for now, think of it as a word or part of a word), and the task of guessing it is next-token prediction. Because every sentence ever written turns into training examples without anyone labelling anything, this is called free supervision.
It's probably easiest to see the idea with a model that doesn't need a neural network at all: it just counts, over some training text, which word followed each word. Here's code that does it for ten words of text. It splits the text into words, then walks through each pair of neighbouring words and adds one to a counter for "this word followed that one". A loop at the end divides each count by the total for that word, so the counts become probabilities.
Try it Learn which word follows which from ten words of text
from collections import Counter, defaultdict
text = "the cat sat on the mat and the cat ran".split()
nxt = defaultdict(Counter)
for a, b in zip(text, text[1:]):
nxt[a][b] += 1 # count what follows each word
for word in ("the", "cat"):
total = sum(nxt[word].values())
probs = {w: round(c / total, 2) for w, c in nxt[word].items()}
print(f"after '{word}':", probs)
the, this model gives cat two chances in three (0.67) and mat one in three (0.33), because the was followed by cat twice and mat once. After cat it splits evenly between sat and ran, at 0.5 each.Check the output against the text. The word the appears three times, followed by cat twice and mat once, so the probabilities are two-thirds and one-third, and cat is followed once by sat and once by ran, which gives an even split. A large language model does the same job, giving a probability to every possible next token, but it uses far more context than the single previous word and a learned function in place of a lookup table. Our counting model also has a weakness we have to get past. It has seen only what's in its ten words, and it looks back exactly one word, so after is it would have nothing at all to say about France.
Why would training on such a modest-looking task teach a model anything worth having? Consider what a model needs in order to be good at it across a large and varied pile of text. To predict the token after "The capital of France is", it has to encode the fact that Paris is that capital. To predict the next line of a step-by-step derivation, it has to track the intermediate state of the problem, and mimicking the surface style of the previous line won't be enough. To predict the next token in grammatical text, it needs an implicit model of syntax. Nobody programs any of this in. It falls out as a side effect of being good at the one task the model was asked to do.
There's a limit to what next-token prediction gives you, though, and it matters for the rest of the chapter. A model trained this way just continues text plausibly. If you ask it a question it might answer, but it might also restate the question, or trail off into a list of similar questions, because all of those follow a question somewhere on the internet. Getting from "plausible continuation of internet text" to "a helpful answer in the right format that stops in the right place" is the job of everything after pretraining, SFT and then RLHF or DPO, and that's most of what's left in this chapter. But before any of it, we need to settle what the model reads, because it isn't words.
02What the model reads
Our counting model split its text on spaces, and splitting on spaces is a poor way to cut text for a bigger model. A vocabulary of whole words has to be enormous to cover every name, typo and technical term, and the first time the model meets a word outside its list it has nothing to put in its place. An LLM reads tokens instead: chunks produced by a subword tokenizer, almost always from the BPE (byte-pair encoding) family. The recipe, in outline, is to start from individual characters or bytes and repeatedly merge the most frequent adjacent pair into a new token.
What comes out is a vocabulary that mixes common whole words ("the" ends up as one token) with pieces of words for anything rarer. Our five-word prompt is probably five tokens, since each word is common, while a rare word gets split into several pieces. Any string can still be represented, because you can always fall back to individual characters or bytes, so there's no "unknown token" escape hatch like the one whole-word vocabularies needed. Next, the tokenizer gives each token in the vocabulary a number, its token id, and a prompt reaches the model as a list of integers.
A list of integers can't go through a neural network directly, since the ids are labels and carry no meaning in their size. So the model owns an embedding table, a grid with one row per token in the vocabulary, each row a list of learned numbers. Looking up the id of a token returns its row, and that row is the vector the rest of the model works with. If the vocabulary has tokens, the table has shape , and it's trained like any other weight. We'll see a second table of the same size at the top of the model in the next section.
That table is where the size of the vocabulary starts to cost something, and it's a real design tradeoff and no free parameter to turn up. A bigger vocabulary packs more meaning into each token, so the same text becomes a shorter sequence and less compute is spent per unit of content, since attention cost grows with sequence length (chapter 08). But a bigger vocabulary costs you twice. Both the embedding table and its twin at the output scale with , and each rare token sees less training signal, because the same corpus spreads its counts across more distinct ids. A smaller vocabulary keeps those tables lean and gives every token plenty of signal, and it burns more of the context budget on ordinary text and shreds rare words, such as a chemical name or a word from a low-resource language, into many small pieces just to represent them.
So we can turn "The capital of France is" into a short list of vectors. What the model does with that list, and how it ends up pointing at "Paris", is the next question.
03The decoder-only stack
In chapter 08 you met two kinds of Transformer block. An encoder block is bidirectional, so every token sees every other token in both directions, and it's the BERT half. A decoder block is causal, so a token sees only itself and whatever came before it. To get an LLM in the GPT, decoder-only sense, we keep only the causal block, stack it 12 to 100 or more times, and put a vocabulary-sized output layer on top. Nothing new is needed. There's no new attention mechanism and no new normalisation trick: we delete the encoder and the cross-attention and stack the piece we already understand.
The causal part deserves a moment on our sentence. During training we ask the model for a prediction at every position at once: the vector at "The" should predict "capital", the one at "capital" should predict "of", and so on up to "is", whose job is to predict "Paris". If the position holding "France" could look at the token that follows it, it would just read the answer off. The fix is a causal mask. Take the block from chapter 08 (LayerNorm, multi-head self-attention, residual add, LayerNorm, feed-forward, residual add) and relabel it almost unchanged. Before the softmax in , every score for a key position after the query position gets set to , so position can only attend to positions .
The diagram below shows the whole stack. Read it from the bottom: token ids become embeddings with position information added (here by RoPE, from chapter 08), the block repeats times, and the feed-forward layer inside uses GELU or SwiGLU as its nonlinearity. Then comes a final LayerNorm and a linear projection from back to the vocabulary size. That's the top of the model. Off to the right, the small 4×4 grid is a toy causal mask, with rows for query positions and columns for key positions. Row 0 sees only itself, row 3 sees everything before it, and that triangle is the entire difference from an encoder block.


Now follow the output. That last projection turns each position's final vector into a list of raw scores, one per token in the vocabulary, called logits, and a softmax turns the logits into a probability for every possible next token. At the position holding "is" in our sentence, we hope the probability for "Paris" is the biggest. To generate text, we pick a token from that distribution, append it to the input, and run the model again, which is the loop at the top of the diagram.
The projection at the top mirrors the embedding table from section 02. Where the table maps each of the ids to a -dimensional vector, the output projection maps a final hidden state back to a -dimensional vector of logits, and the softmax turns that into the next-token distribution. Both matrices are the same shape transposed, so it's common to share the weights between them, a trick called weight tying. It cuts a real chunk of parameters, since these tables can be a large fraction of the total in smaller models, and it tends to regularise training, because the same vector now has to work both as what this token means going in and as what this token would mean coming out.
Why decoder-only, and not the full encoder-decoder?
An encoder-decoder makes sense when the input and the output are structurally different sequences with a clean split, such as a source sentence and a target sentence in translation, or a document and its summary. A general-purpose assistant has no such split. The task might be a question, a document to summarise, code to complete or half a conversation, and the boundary between prompt and completion is wherever generation happens to start, with nothing in the task itself marking it. A decoder-only model treats the prompt as a prefix of the same sequence as the completion, processed by the same weights and the same causal attention as the response. With no fixed input/output split built into the architecture, one model handles completion, question-answering, chat and code without changing shape.
It also fits in-context learning well. Its whole context (instructions, examples, the new query) is one sequence that the model attends to causally, so it reads a few examples immediately before it generates, and that's what GPT-3's few-shot prompting exploits. We now have an architecture with random weights, and what's left to settle is the number it should be trained to push up.
04The training objective
At every position, the model hands us a probability for each possible next token, and training has to reward it for putting probability on the token that came next. Say the training text contains "The capital of France is Paris". At the position holding "is", the model gives "Paris" some probability . We want close to 1, so how should we score it? We use . That score is 0 when and grows without limit as shrinks. A model that gave "Paris" two chances in three, like our counting model did for cat after the, would score on that position. Adding that up over every position in the training sequence gives the loss:
Reading the symbols from the left, is the training sequence, and the same tokens serve as the input and, one position later, as the label, so no separate annotation exists or is needed. is the probability the model assigns to the actual next token, read straight off the softmax over the vocabulary-sized logits at position . Summing over is where the causal mask pays off. Because no position can see its own answer, every position's prediction can be computed in one parallel forward pass, a setup called teacher forcing, and one sequence of length yields training signals for free. Minimising is the same as maximising the likelihood the model assigns to the real continuation of the text it was trained on, and nothing more exotic than that is happening during pretraining.
That settles what a training step does. How big the model should be, and how much text it should see, is a separate question, and it has a surprisingly precise answer.
05How much model, how much data
Training compute is well approximated by FLOPs, where a FLOP is one floating-point operation, is the parameter count (the number of learned weights) and is the number of training tokens. That 6 comes from roughly 2 FLOPs per parameter per token on the forward pass and another 4 on the backward pass. So the budget is the product of model size and data, and for a fixed budget we have to choose how to split it.
Before 2022, the assumption behind most large-model training was that a bigger model is a better model, so a fixed budget went mostly into , and the model trained on whatever happened to fit the schedule. Hoffmann et al.'s Chinchilla paper (2022) tested that directly. They trained over 400 models across a range of sizes and token counts, and fitted how the loss depends on both under a fixed compute budget. Their finding was that loss is minimised when and scale together, roughly in proportion, and that works out to about 20 training tokens per parameter in their fitted regime. Maximising alone isn't the answer.
If compute is fixed, what gives?
With held fixed, it's a tradeoff in both directions. Spend the budget on a bigger model and has to shrink, and spend it on more data and has to shrink. Chinchilla itself was a 70B-parameter model trained on roughly four times more tokens than Gopher (280B parameters), for the same training compute. It beat Gopher, GPT-3 and other larger contemporaries trained on the older size-heavy recipe. The practical consequence is that model size and data budget aren't separable choices you can make in isolation, and a model that's big enough but starved of tokens for its size is, in Chinchilla's own framing, substantially undertrained.
Whatever split we choose, all of this compute goes into the same objective, so what comes out the other end is the text completer from section 01. Turning it into an assistant is a separate stage, and it's much cheaper.
06From completer to assistant: SFT
The whole pipeline has four stages, and the diagram below lays them out in order. Pretraining is next-token prediction on raw text, trillions of tokens of it, and it takes weeks and most of the compute budget. SFT comes next, then preference optimization, and each stage takes the model from the previous one and changes what it's optimised for. The last box, deployment, is where the weights get quantised or distilled and served, which we'll reach in section 08.
A freshly pretrained model is a very good predictor of whatever plausibly follows a piece of text. Give it "What is the capital of France?" and answering is one plausible continuation, but so is restating the question, imitating a bad forum reply, or trailing off, because all of those are plausible continuations of internet text too. So we need to move the model's idea of "plausible" toward what we want. SFT, supervised fine-tuning, does that with the same next-token-prediction loss from section 04, applied to a different and much smaller curated dataset. Each example is an instruction paired with an ideal response, usually written or vetted by humans, in a consistent template, and the model is trained to predict the response tokens given the instruction.
Notice how little changes. There's no new architecture and no new loss, just a shift in what counts as a plausible continuation. That step alone turns a raw completer into something that reliably answers in the right format and stops in the right place. Later stages refine which of several plausible SFT-style answers people prefer, and they don't teach instruction-following from scratch. And that raises the next question: if two answers are both correct and both on-format, how does the model learn which one to give?
07Learning what people prefer: RLHF and DPO
Ask our assistant "What is the capital of France?" and it could reply "Paris." or it could reply with a paragraph on the city's history. Both are correct and both are well formed, so SFT, which supervises a single ideal response per instruction, has nothing more to say. People will probably differ on whether they want concise or thorough, direct or hedged, correct-but-blunt or correct-and-tactful. That's a preference and not a fact you can supervise with one correct label. Preference data usually comes as a preference pair: a prompt, with a response a person preferred and one they didn't. Two recipes turn such pairs into a better model.
The first is RLHF, reinforcement learning from human feedback, used for InstructGPT (2022). It starts by training a separate reward model on human-labelled comparisons ("given two responses to this prompt, which do you prefer?"), so that the reward model learns to give a number to any response. Then it runs an actual reinforcement-learning loop, using an algorithm called PPO, that updates the SFT model toward outputs with a higher reward. A KL penalty charges the model for moving its output distribution away from where SFT left it, and that holds the model close to its SFT starting point so it doesn't drift into degenerate, reward-hacking territory, where it finds outputs that score well without being better. That makes three models trained in sequence: the SFT model, a reward model trained on human preference pairs, and a policy optimised against that reward model. That last stage is a genuine RL loop, with rollouts (responses the model generates during training), a value function and clipping, and with the usual RL instability and risk of reward hacking.
That's a lot of machinery, and the second recipe asks whether we can skip some of it. DPO, direct preference optimization (2023), reaches the same alignment objective through a mathematical shortcut.
Where does the reward model go?
The optimal policy for the same KL-constrained RLHF objective has a closed form, an explicit formula, directly in terms of the reward function. Substitute that formula into the Bradley-Terry preference model (a standard way to turn two scores into the probability that one response beats the other) that was already used to train the reward model, and the reward model cancels out algebraically. What's left is a loss defined purely on the policy's own likelihoods for preferred and dispreferred responses:
Here is a prompt and is a human-labelled preference pair, with the preferred ("winning") response and the dispreferred ("losing") one. is the policy being trained, and is a frozen reference model, almost always the SFT checkpoint from before preference tuning starts. Each log ratio says how much more or less likely the current model makes a response compared to where it started, and that's the quantity being pushed around, since a raw probability wouldn't say anything about movement. controls how hard to push. A higher trusts the preference data more and allows a bigger departure from , and a lower one keeps the model closer to its starting point, and that's the same role the KL penalty plays in RLHF. The sigmoid turns the gap between how far the winning response's relative likelihood moved up and how far the losing response's moved up into a probability that this pair is correctly ordered, and the loss is binary cross-entropy on that probability against "yes, correctly ordered."
The net effect is to push up the relative likelihood of preferred responses and push down that of dispreferred ones, with no separate reward model and no RL rollout loop. The reward is implicit in the likelihood ratio itself, the "secretly a reward model" of the paper's title. So DPO reaches the same alignment objective in theory with one supervised-style training loop in place of the separate reward-model and PPO stages, with no reward model to maintain and no PPO rollouts. That's why DPO and its descendants spread quickly through open-source and production fine-tuning pipelines after 2023. The table puts the two side by side.
| RLHF (PPO) | DPO | |
|---|---|---|
| Training complexity | 3 stages: SFT, reward model, PPO policy optimization | 2 stages: SFT, then a direct preference loss |
| Stability | Genuine RL training — sensitive to hyperparameters, can diverge or reward-hack | Supervised-style loss — generally more stable to train |
| What you need | A separate reward model plus RL infrastructure: rollouts, value function, PPO clipping | Just the preference-pair dataset and a frozen reference copy of the SFT model |
| Typical use | Frontier labs with engineering budget for more explicit control over the reward signal | Default choice for most open-source and production fine-tuning pipelines |
With the model trained and aligned, we have the whole recipe for an assistant. What we haven't looked at is the bill: a model this size is expensive to adapt to a new task and expensive to run, and there are a few standard ways to bring those costs down.
08Making it cheaper to adapt and run
Quantization and LoRA solve two different problems, and they get conflated because they're often used together. We'll take them one at a time, then a third lever that changes the architecture, and then what happens when the model is finally serving requests.
Quantization
Quantization is a deployment lever. You take an already-trained model's weights, stored in 16-bit floating point, and represent them with fewer bits: 8-bit, 4-bit, sometimes lower. That shrinks the memory footprint and often speeds up inference, at the cost of some numerical precision. It comes in two variants. Post-training quantization (PTQ) happens after training with no gradient updates, only a calibration pass to pick good quantization ranges. It's cheap, and the quality loss is usually small but uneven, since arithmetic and rare factual recall tend to degrade first. Quantization-aware training (QAT) simulates the quantization during training, so the weights adapt to the precision loss as they're learned. You get better accuracy at the target precision, and you pay for it with an actual training run.
LoRA and QLoRA
LoRA is an adaptation lever, and it does nothing for deployment. Ordinary fine-tuning updates all of a pretrained model's weights. LoRA freezes the base weight matrix entirely and learns a small low-rank update alongside it, , where , , and the rank is tiny compared to and . You back-propagate into only and , a tiny fraction of the parameter count. That drastically cuts optimizer memory and lets you store and swap many task-specific adapters against one shared frozen base.
QLoRA combines the two levers. It quantizes the frozen base to 4-bit to shrink memory further, then runs LoRA fine-tuning on top of that quantized base, and that's what makes fine-tuning a large model feasible on a single consumer-class GPU.
Mixture-of-experts
A third lever goes after the feed-forward layer from section 03. In a dense Transformer, that layer runs every token through the same weights, so more parameters there means more compute for every token without exception. MoE, mixture-of-experts, breaks that coupling. It replaces the single feed-forward layer with a bank of parallel expert feed-forward layers plus a small learned router, and for each token the router selects only the top- experts (commonly 1 or 2) to run:
Here is the router's weight for expert on input , and is that expert's output. Only the selected experts do any compute, and the rest cost nothing for that token. A model can therefore have an enormous total parameter count spread across all its experts, while the compute per forward pass reflects only the handful activated. It costs you in training, though. Without an auxiliary load-balancing loss encouraging the router to spread tokens evenly, it collapses onto a favourite few experts, and you lose the benefit you paid to build.
Serving
Two things about serving shape how you reason about training and architecture choices. The first is the KV cache, introduced in chapter 08. During autoregressive generation (the append-and-repeat loop from section 03), the model caches every past token's key and value vectors instead of recomputing attention over the whole prefix at every step. For long conversations it's often the dominant memory consumer on a serving GPU, so it's now a first-class cost of running an LLM product. Second comes batching. A serving system groups several requests together so the GPU processes them in parallel, trading a little per-request latency for much higher throughput. A deeper systems treatment (paged attention, continuous batching, tensor and pipeline parallelism, and quantization-for-serving tradeoffs) lives in chapter 23, Efficient AI & Systems. This chapter covers only what you need to reason about training and architecture tradeoffs, and leaves out how to operate a serving fleet.
That covers the main line from raw text to a served assistant. A handful of other pieces turn up around it in practice, and it helps to know where each one fits.
09Other pieces around the pipeline
Each of these touches a different stage of the pipeline we just walked through, and each one is a short note on where it fits.
Data quality, deduplication and mixture design. A pretraining corpus isn't just all the text you can find. Near-duplicate documents inflate a dataset without adding signal and push the model toward memorising repeated substrings, so deduplication is a standard pipeline step, and it measurably improves quality per token spent. Mixture design, meaning what fraction of tokens come from web text, books, code or curated sources, meaningfully shapes what the model is good at. A heavier code mixture improves structured reasoning, and that's no accident, because code text rewards tracking state precisely.
Long-context training. A model pretrained mostly on short documents doesn't automatically use a 128k-token window well just because attention can mathematically handle it (chapter 08 covers attention sinks and mid-context dilution). Labs run dedicated long-context stages, often extending the position embeddings and training on long documents, to make the model exploit long context instead of merely tolerating it.
Function and tool calling. This is a trained or prompted behaviour where the model emits a structured request, such as "call this API with these arguments", in place of answering purely from its own weights, and then consumes the tool's result before producing a final answer. It's what turns a text predictor into something that can look things up, run code or take actions, and it's the foundation of chapter 11 (RAG and agents).
Structured and constrained decoding. This is an inference-time technique and changes nothing in training. Instead of hoping free-form output happens to be valid JSON, you constrain the token-by-token sampling itself so that only tokens consistent with a target grammar are ever eligible. That's a decoding-time guarantee that the output can't be unparseable, with no retraining.
Code, multilingual and domain models. Code models are typically the same decoder-only architecture, pretrained or fine-tuned with a much heavier proportion of source code, and often trained to fill in the middle of a file as well as continue it left to right. Multilingual and domain models face the tokenization tradeoff from section 02 most acutely. A tokenizer trained mostly on English badly over-fragments other languages and specialised vocabularies such as legal text or chemistry, quietly costing context budget and quality, unless the tokenizer and the pretraining mixture are built for that domain from the start.
Distillation, merging and pruning. Distillation trains a smaller student model to match a larger teacher's output distribution. It's a genuine training run, but it typically preserves more capability per parameter than quantizing the teacher down to the same footprint. Merging averages or interpolates the weights of several fine-tuned variants of the same base model directly, with no training, and it works surprisingly often when the variants stayed close to the same base. Pruning removes the weights or structures judged least important, usually followed by a short fine-tune to recover quality, and for modern LLMs it's the least reliably clean win of the three.
Every stage we've covered has a way of going wrong, and the last question is which of those failures show up in production.
10What goes wrong
Two of the failures come from the preference stage in section 07, and two from the efficiency levers in section 08. Reward hacking happens when the policy finds outputs that score well on an imperfect reward model or preference signal without being better. Longer answers, hedging language and sycophantic agreement are the usual examples, because they correlate with human preference ratings even though they aren't more correct. A related problem is overfitting to a narrow annotator population. Preference data reflects the taste, culture and instructions given to whichever pool of annotators labelled it, so the aligned model inherits those biases as if they were universal, and "helpfulness" quietly comes to mean what that specific pool liked.
Quantization has its own cost. Lower precision trades a usually small, but uneven, amount of task accuracy for large memory and compute savings, and arithmetic and low-frequency facts tend to degrade before fluent generation does. In a mixture-of-experts model, an unregularised router collapses onto a favourite handful of experts, wasting the extra capacity and effectively shrinking the model back toward its active-parameter count. That's why MoE training adds the auxiliary load-balancing loss term from section 08.
As for where things stand in 2026, reasoning-focused post-training is an active, fast-moving research area. It adds extra RL or search-based training aimed specifically at multi-step problem solving, layered on top of the SFT, RLHF and DPO recipe described here, and preference-optimization variants that go beyond vanilla DPO are moving just as fast. It's probably best to treat the exact recipe used by any specific current model as a moving target. The underlying building blocks (pretraining, SFT, preference optimization, quantized deployment) are stable enough to learn thoroughly, whichever variant is fashionable this quarter.
11Summary
- Next-token prediction is free supervision. Any text cut at any point gives an input and a label, so "The capital of France is" and "Paris" come out of ordinary text with nobody labelling anything.
- Doing that well forces the model to learn a lot. Facts, intermediate state in a derivation and syntax all help predict the next token, and none of them are programmed in.
- The model reads tokens, not words. BPE merges frequent pairs into subword pieces, each piece gets an id, and an embedding table turns the id into a vector. Vocabulary size trades shorter sequences against bigger tables and less signal per rare token.
- An LLM is the causal half of the Transformer, stacked. Masking future scores with is the one structural change from an encoder, and a vocabulary-sized output layer, often weight-tied to the embedding table, turns the last vector into next-token logits.
- Decoder-only won because a prompt is just a prefix. One model handles completion, question-answering, chat and code, and few-shot examples sit in the same sequence as the query.
- The loss is the negative log-probability of the true next token. The causal mask lets every position be trained in parallel, so a sequence of length gives training signals.
- Size and data have to grow together. With , Chinchilla found about 20 tokens per parameter, so many earlier large models were undertrained for their size.
- SFT turns a completer into an answerer. It uses the same loss on a small curated set of instruction and response pairs.
- Preference optimization chooses between good answers. RLHF trains a reward model and runs PPO with a KL penalty, and DPO cancels the reward model out algebraically and optimizes one supervised-style loss against a frozen reference.
- Quantization, LoRA and MoE attack different costs. Quantization shrinks deployed weights, LoRA and QLoRA cut the cost of fine-tuning, and MoE decouples parameter count from compute per token.
- Each lever has a failure mode. Reward hacking, annotator bias, uneven accuracy loss from quantization and router collapse in MoE are the ones that show up in production.
12Build this
A scaling law reads like a claim about somebody else's compute budget. Three small training runs on your own laptop turn it into a line you drew yourself.
Train the same decoder-only model at three sizes on one small corpus, then plot final validation loss against parameter count on log axes. The task is ordinary next-token prediction, and the samples are not the interesting part. The shape of the three points is, because that shape is section 05's scaling argument drawn from runs you can afford.
- Take a few megabytes of plain text. Anything with consistent style works: one book, one codebase, one set of transcripts. Hold out a slice for validation.
- Train a BPE tokenizer on that corpus with a small vocabulary, a few thousand merges. Print the merge list in order and read the first hundred. Watch characters assemble into common suffixes, then into whole words.
- Build the decoder block by hand from the diagram in section 03: LayerNorm, masked self-attention, residual add, LayerNorm, feed-forward, residual add. Write the causal mask yourself with
torch.tril. Nonn.TransformerDecoder. - Train three models that differ by roughly an order of magnitude in parameter count each, varying width and depth. Same data, same number of tokens seen, same optimizer, same schedule. Only size changes.
- Plot final validation loss against parameter count with both axes log-scaled. Sample a paragraph from each model and read them side by side.
- Now break it deliberately. Delete the causal mask from the smallest model and retrain.
Where this runs in production
A modern assistant product's pipeline maps onto this page almost exactly:
- Pretraining. Web-scale next-token prediction builds the base model's broad knowledge and language competence.
- SFT. Curated instruction-response pairs teach it to answer on-format.
- Preference optimization. RLHF or DPO, using human or model-assisted preference judgments, teaches it which of several plausible answers people want.
- Deployment. The resulting weights are quantized, and sometimes distilled into a smaller model, to make serving affordable, with KV-cache and batching handling request-level efficiency (full treatment in 23).
Everything sitting on top at inference time (a system prompt, tool/function-calling scaffolding, retrieval) is applied to this already-trained stack and is not baked into training. That is where 11 picks up.
13Interview questions
BeginnerWhat's the actual training signal used to pretrain an LLM, and where do the "labels" come from?
Every token in a training sequence is simultaneously an input (for predicting later tokens) and a label (the correct answer for predicting it, given everything before it). Teacher forcing exploits this directly: feed the model the true previous tokens, ask it to predict the next one, compute cross-entropy against the actual next token, and repeat for every position in the sequence in parallel via the causal mask. No human labels this data — the label is just "whatever token comes next in text that already existed" — which is why pretraining can use effectively the entire scrapeable internet as its own supervision.
BeginnerWhat's the one structural difference between the encoder blocks in 08 (BERT) and the blocks used in a GPT-style LLM?
Causal masking. A decoder-only block adds a mask before the softmax that sets the score for any key position after the query position to , so a token's attention output can only depend on tokens at or before it. An encoder block has no such mask — every token attends to every other token, forward and backward. Everything else — Q/K/V projections, multi-head split, residual connections, LayerNorm, the feed-forward layer — is identical.
IntermediateExplain the difference between RLHF and DPO.
RLHF trains a separate reward model on human preference pairs, then runs PPO — an actual RL loop with rollouts, a value function, and clipping — to optimize the policy against that learned reward, with a KL penalty holding it near the SFT model. DPO skips both the reward model and the RL loop: it shows the optimal policy for that same KL-constrained objective has a closed form in terms of log-probability ratios between the trained policy and a frozen reference policy, so preference pairs can be optimized directly with one supervised-style loss. Same underlying alignment objective, reached with far less machinery and instability — at the cost of somewhat less explicit control over the reward signal.
IntermediateWhy would you reach for LoRA instead of full fine-tuning?
LoRA freezes the entire pretrained weight matrix and learns a small low-rank update, , updating only and — orders of magnitude fewer parameters than the full model. That means far less optimizer state in memory, a much smaller checkpoint per fine-tuned task, and the ability to swap adapters in and out of one shared frozen base at serving time. Full fine-tuning still wins on raw quality ceiling when you have the compute and data to justify it; LoRA (and QLoRA, which additionally quantizes the frozen base to 4-bit) is about making adaptation cheap, not about beating full fine-tuning outright.
IntermediateWhat does a mixture-of-experts layer change about the forward pass compared to a dense FFN?
A dense FFN runs every token through the same weights, so more parameters means more compute per token, always. An MoE layer replaces the single FFN with many parallel expert FFNs plus a router that picks the top-k experts (often 1 or 2) per token — only those experts do any compute for that token. This decouples total parameter count from compute-per-token: the model can have a huge total parameter count spread across experts while any single forward pass only touches a small fraction of them. The catch is the router — without a load-balancing loss it collapses onto a favorite few experts and the extra capacity goes to waste.
DeepWhy do Chinchilla-style scaling laws matter for a training budget decision?
Because compute is the actual constraint, and Chinchilla showed loss is minimized under a fixed compute budget by scaling model size and training tokens together — roughly 20 tokens per parameter in their fitted regime — not by maximizing parameters and undertraining on whatever data fits. Pick a model twice as large as compute-optimal for your budget and you're forced to train it on fewer tokens than compute-optimal, ending up worse than a smaller model trained longer on the same budget — which is exactly what several pre-2022 large models did, by Chinchilla's own comparisons. Practically: the model-size decision and the data-budget decision aren't separable — you size the model to the compute and quality data you actually have.
DeepYou need a 70B-quality model to run in a 15B-model's memory footprint. What are your options, and what does each cost you?
Quantization: compress the same weights to lower precision, cutting memory roughly 2–4x with typically small but non-uniform accuracy loss. Distillation: train a genuinely smaller model to mimic the larger model's output distribution — a real training run, but it usually preserves more capability per parameter than quantization alone. Pruning: remove weights or structures judged least important, then fine-tune to recover quality — the least reliably clean win of the three for modern LLMs. Or start over: per Chinchilla, a smaller model trained compute-optimally can beat an undertrained larger one at the same budget. In practice: quantize first since it's the cheapest and most reliable win, layer in distillation or a purpose-trained smaller model if that's not enough, and benchmark on your actual task, since accuracy loss from any of these is rarely uniform across tasks.
DeepWhy can pushing a preference-optimization objective too hard make a model worse, even though the reward or preference signal keeps improving?
The reward model (RLHF) or the implicit preference signal (DPO) is a proxy for what humans actually want, not the thing itself — and proxies can be gamed. Optimize too aggressively against a reward model, or let DPO's get too permissive relative to the reference model, and the policy finds outputs that score well on the proxy — longer answers, hedging, sycophantic agreement — without those outputs being more correct or useful. That's reward hacking, and it's exactly why RLHF keeps a KL penalty (and DPO's plays the same role) tethering the policy back to the reference model. Weaken that tether and gains on the training signal can actively diverge from real quality.
14Go deeper
●Now write it yourself
Reading the derivation and being able to produce it are different skills. These are Deep-ML problems that exercise what this page covers — each one is checked against real test cases, not multiple choice.
Matched to this page from Deep-ML's catalogue of 1,380 problems. More at deep-ml.com, and Where to practise covers the other platforms and what each one trains.