Skip to main content

Layer L2

LLM core

  1. + A vast slice of the internet

    1Pre-training

    A base model that continues any text

  2. + Examples of good answers

    2Instruction tuning

    An assistant that answers

  3. + Preferences and rewards

    3Reinforcement learning

    A more helpful, careful assistant

  4. + Your own examples

    4Fine-tuning

    A model for your task

The layer

What this layer is about

This layer is the heart of the whole map. Behind the chatbot you use every day is a large language model. When you finish this layer, you should be able to tell the story of "how a large model is made" from start to end: how text becomes numbers the model can read, how the model computes, how it learns to talk from huge amounts of text, how it is then tuned into an assistant that answers questions, and finally how each word is chosen. And at every step you should be able to say "why it is done this way".

As standards you can check, that is two things: you can write and train a small GPT from scratch, and you can walk an interviewer through the whole pipeline from pretraining to alignment.

This layer changes slowly. The Transformer's skeleton and the training goal of "predict the next token" have barely changed since the Transformer was proposed in 2017. What changes is the recipe: how the data is cleaned, how scale is balanced, which post-training methods are used, whether to use MoE. So one review a year is enough; there's no need to chase it every quarter.

The map of this layer

Start by remembering one sentence: a large language model does only one thing. Give it a string of tokens (the smallest unit a model reads and writes, roughly a word or part of a word), and it computes a probability table for the next token. The entry node, LLM: how the model works, is about exactly that sentence, and about how this one job decides where the model will make mistakes. All the other nodes are parts of that job, in the order text flows through the model:

  • Tokenizer: how text becomes integer IDs. The mainstream method is byte-level BPE: start from bytes, and repeatedly merge the two adjacent pieces that most often appear together into a new piece. The vocabulary sets the size of both ends of the model, and also explains why models can't count letters or do arithmetic well.
  • Transformer: the model itself, which turns a string of tokens into a probability table for the next token. Attention lets every token look directly at every other token; residual connections and layer normalization let it be stacked very deep. This layer's reproduction project is attached here.
  • Pretraining and scaling: training a Transformer whose parameters are all random numbers into a real model, by practicing "guess the next token" on huge amounts of text. Scaling laws tell you that if you spend more compute and feed more data, the loss (a score for how wrong the guesses are) goes down along a predictable curve. Chinchilla went further and worked out how to balance parameters and data when compute is fixed.
  • Fine-tuning: teach it your task and Post-training: shaping with rewards: post-training. A pretrained model can only continue text. SFT (supervised fine-tuning) uses demonstrations to teach it the format of an answer, RLHF / DPO use human preferences to teach it to answer better, and rewards that can check right and wrong automatically teach it to solve problems step by step. Together these are what people call "alignment".
  • Decoding and inference: choosing a token from the probability table. Temperature and top-p are the knobs for "play it safe or loosen up". This node also covers why answers come out one word at a time, and how the KV cache and speculative decoding make that a bit faster.
  • Long context and MoE and Multimodal: two kinds of change to the skeleton. The first bargains with attention's quadratic cost, and decouples the model's parameter count from the compute spent on each token; the second encodes images and sound as tokens and puts them in the same sequence.

Told as one line, this is the question interviews ask most often: tokenizer → Transformer → pretraining (scaling) → SFT → RLHF / DPO → decoding.

What you can skip for now

  • You can skip the encoder-decoder architecture and the BERT family (the other branch, good at understanding text and bad at generating it) for now, and learn only today's mainstream decoder-only design; knowing they exist is enough.
  • You don't need to read the original paper first: write a GPT along with the videos, then read "Attention Is All You Need", and only then will it make sense.
  • For scaling laws you only need the conclusion and one figure from the Chinchilla paper; you don't need to reproduce the power-law fits yourself.
  • You don't need to learn reinforcement learning systematically from scratch: the PPO / GRPO used in post-training (the specific algorithms that turn rewards into parameter updates) are covered well enough in the RLHF book.
  • The engineering of inference systems (how the KV cache is implemented, how batching works, how quantization works) belongs to L3; this layer covers only the concepts.
  • For multimodal you only need to know the two ways of connecting it; you don't need to chase the latest models.

Top picks

In reading order; each pick links to its node below.

  1. 1

    Deep Dive into LLMs like ChatGPT — Andrej Karpathy free

    Three and a half hours covering the whole path from token to RLHF. You get the big picture first; every node afterwards zooms in on one part of it → LLM: how the model works

  2. 2

    minbpe free

    Write BPE yourself once, and from then on you can explain why models can't count letters and why some languages cost more tokens → Tokenizer

  3. 3

    Let's build GPT: from scratch, in code, spelled out. free

    Two hours, from the simplest "guess the next character from the previous one" up to multi-head attention. When you finish, you've met this layer's first finish line → Transformer

  4. 4

    LLMs-from-scratch free

    Breaks "implement and train a GPT from scratch" into chapter-sized steps you can check yourself, all the way to instruction tuning → Transformer

  5. 5

    CS336: Language Modeling from Scratch free

    A full Stanford course. Each lecture covers one part of the pipeline and the homework is to build it yourself. Good as an outline for the whole pipeline → Pretraining and scaling

  6. 6

    Training Compute-Optimal Large Language Models free

    Afterwards you'll see where "about 20 tokens per parameter" comes from, and why it changed the balance of parameters and data in the models that followed → Pretraining and scaling

  7. 7

    Hugging Face LLM Course free

    Fine-tune a small model with an off-the-shelf library and see with your own eyes what SFT training data looks like → Fine-tuning: teach it your task

  8. 8

    RLHF book — Nathan Lambert free

    Reward models, PPO, DPO and verifiable rewards, one chapter each. Your script for explaining post-training to an interviewer → Post-training: shaping with rewards

  9. 9

    Generation strategies — Transformers documentation free

    Run greedy, sampling and beam search once each, and temperature and top-p turn from words into knobs you have a feel for → Decoding and inference

  10. 10

    Mixtral of Experts free

    A short paper on how the MoE router picks experts, and why "active parameters" are so much fewer than total parameters → Long context and MoE

The nodes

LLM: how the model works

Who asks for it

llmdecoding-and-inferenceembeddingsfrontier-on-demandfrontier-weeklyno prerequisite

A large language model (LLM) is a program that does only one thing: give it some text, and it computes a probability table for "what the next token is". A token is the smallest unit a model reads and writes, roughly a word or half a word (for how text is cut into tokens, see Tokenizer). The whole answer you see in a chat window was built one token at a time: guess one, append it to the end, then use the whole text to guess the next.

An example

Give it "Twinkle, twinkle, little", and in the probability table the model returns, "star" may take almost all of the probability, with a little left over for other words. Pick "star", append it, feed the whole "Twinkle, twinkle, little star" back in, and guess the next one. The machine that computes this table is the Transformer; how to pick from the table is the business of Decoding and inference. When a model seems to "know facts" or "reason", in the end it is because this table comes out accurate enough in all kinds of situations.

How it is made: two steps

  • Pretraining: have the model read a huge swath of text from the internet and, at every position, practice guessing the next token; when it guesses wrong, its internal parameters (billions of numbers) get adjusted slightly. The result is a base model: it can continue any text, but it doesn't yet "answer". Ask it a question and it may go on to write three similar questions, because on the web a question is often followed by more questions (Pretraining and scaling).
  • Post-training: first show it a large number of "question → good answer" demonstrations, so it learns the format and tone of an answer (Fine-tuning: teach it your task); then have it answer the same question several times, have people or programs score the answers, and push it towards the higher-scoring ones (Post-training: shaping with rewards). That is how a base model becomes an assistant.

Why you need to understand this first

Because it decides where the model will go wrong, and the mistakes follow a pattern:

  • Bad at counting and spelling: the model sees tokens, not letters. Asking it "how many r's are in strawberry" is asking it to count something it cannot see.
  • Fuzzy memory: knowledge was squeezed into the parameters during pretraining, and that compression is lossy. Obscure facts, and anything that happened after the training data was cut off, are unreliable.
  • Forgets when the context gets long: there is a limit on how much text it can read at once, called the context window, and even inside the window it may not use everything well (Long context and MoE).
  • Sounding confident is not being right: its training goal is to write "a plausible next passage", not "a true next passage". It can make up things it has never seen, fluently. This is called hallucination.

How it connects to other nodes

This node is the starting point of the whole map. The other L2 nodes are its parts, in the order text flows through the model: cut into tokens (Tokenizer) → the Transformer computes the probability table (Transformer) → pretraining (Pretraining and scaling) → post-training (Fine-tuning: teach it your task, Post-training: shaping with rewards) → picking a token from the table (Decoding and inference); Long context and MoE and Multimodal are modifications to the skeleton. All of L4's application engineering is built on top of it: writing prompts (Prompting: instructions you can measure), adding retrieval (RAG: look up first, then answer) and building agents (Agent: a model with tools in a loop) are, to a large extent, ways of using or working around the mistakes above. If you look at only one thing on this page, make it the video below the text: it goes all the way from tokens to post-training, without skipping the parts that explain "why the model makes mistakes".

Leads to
Decoding and inference · Embedding: turning meaning into vectors · Look up when needed: frontier reference list (≤ 15) · Weekly reads: the frontier feed (≤ 5) · Calling a model API: token, streaming, tools, cost · Serving: running models yourself · Tokenizer
On the routes
Foundations (How the models work)
  • Deep Dive into LLMs like ChatGPT — Andrej Karpathy free

    video · 3.5 hours — Three and a half hours from tokens to RLHF, from one of OpenAI's founding members — the mental model every later choice rests on.

  • AI Engineering — Chip Huyen · O'Reilly paid

    book · about 3 hours · only ch. 2 — Chapter 2 is this skill — training data, architecture, post-training, sampling — for people who build on models; the rest is the AI Engineer track at length: evals, RAG, agents, cost.

Hands-on project: Ship one LLM feature end to end — Structured output with schema validation, streaming, a fallback model, and per-request cost and latency logged — then write down the numbers.

Not picked (4)
  • Stanford CS336 — Already a candidate for Pretraining and scaling; it is the "hands-on version" of this node, where you implement every part yourself.
  • Raschka「Build a Large Language Model (From Scratch)」 — Already a candidate for Transformer.
  • Jay Alammar「The Illustrated GPT-2」(2019) — Well illustrated, but Karpathy's long video covers its content and is more recent.
  • Hugging Face LLM Course — Already the introductory pick for Fine-tuning: teaching it your task.

Tokenizer

llmtokenizerpretraining-and-scaling

A tokenizer is the step that cuts text into small pieces and then swaps each piece for an integer ID. The model never sees the characters, only this list of IDs. Each piece is called a token, and the set of all possible pieces is called the vocabulary.

For example, the English word "unbelievable" might be cut into three pieces, "un", "believ" and "able", while the common word "the" is a piece on its own; for Chinese, in many vocabularies a common character is one piece, while a rare character may instead be split into two or three. What the model finally sees is a list of numbers like [403, 18832, 481].

How to cut: BPE

The mainstream method is called byte-level BPE (byte pair encoding). Start from the smallest unit, the bytes a computer stores text in, count which two neighboring pieces appear together most often in the corpus, merge them into a new piece and add it to the vocabulary; then repeat until the vocabulary reaches a preset size. It is a bit like taking notes: once you have written a long word often enough, you make up an abbreviation for it. The result is that common words are one whole piece, rare words are split into several, and any text at all (emoji, code, new words never seen before) can be spelled out, so there is never an "unknown character".

What it solves, and what it brings

Cut by single characters, and sequences get too long, so the model has to compute many more steps; cut by whole words, and the vocabulary is endless, and a word never seen before cannot be represented. BPE is a compromise between the two. The cost is a set of odd-looking flaws:

  • Bad at counting and spelling: the model sees two IDs, "straw" and "berry", and cannot see how many letters are inside.
  • Chinese is often more expensive than English: when the corpus used to train the tokenizer is mostly English, English gets merged thoroughly while Chinese is cut into smaller pieces, so the same meaning takes more tokens. An API that charges per token costs more, and the context window fills up faster.
  • Numbers are cut arbitrarily: "1234" might be one piece or two, and arithmetic suffers for it.
  • Training data and tokenizer don't match: some tokens in the vocabulary almost never appeared while the model was being trained, so the model knows next to nothing about them, and strange things happen when it runs into one. Many cases of "the model suddenly got dumber for no reason" are only explained once you trace them back to here.

How it connects to other nodes

It is the first gate of LLM: how the model works. The vocabulary size directly sets the size of both ends of the model: at the input, each ID is looked up in an embedding table to get a list of numbers (a vector) to hand to the model; at the output, the model gives a score to every token in the vocabulary. Both tables are as big as the vocabulary (Pretraining and scaling). At each decoding step, what gets picked is also an ID, which the tokenizer turns back into text (Decoding and inference). The fastest way to learn it is to write BPE yourself: the code is short, and once you have written it, you can explain every flaw above.

Builds on
LLM: how the model works
Leads to
Pretraining and scaling
  • minbpe free

    repo · 3 hours coding along — Minimal byte-level BPE, few hundred lines: train, encode, decode, GPT-4 regex split. Build it to explain token counts per model and why arithmetic and spelling fail. First GPT-from-scratch part.

Hands-on project: Train your own tokenizer — Use minbpe to train a 1k-vocabulary BPE on a mixed Chinese-English corpus. Compare its token count with GPT-4's cl100k on the same Chinese text, and explain where the gap comes from.

Not picked (3)
  • Karpathy「Let's build the GPT Tokenizer」视频 — Already the intro pick for Calling model APIs: token, streaming, tools, cost (0:00–14:56), so not repeated here; minbpe is its code version.
  • Hugging Face LLM Course ch. 6 — It shows how to train a tokenizer by calling an existing library, not the principles; it comes from the same source as the course introduced in Fine-tuning: teach it your task.
  • SentencePiece 论文 — Heavy on engineering details; read it when you need it, once you understand BPE.

Transformer

linear-algebrabackprop-and-losspytorchtransformerai-history-scalinglong-context-and-moemultimodalparallel-training

The Transformer is the skeleton of almost every large language model today: a way of building neural networks, proposed in 2017 by a team at Google in the paper Attention Is All You Need. GPT, Claude, Llama, and ViT, which looks at images, are all modifications built on it.

Start with a sentence: "Tom returned the book to Mary, because she has an exam tomorrow." How do you know "she" is Mary? You glanced back over the earlier words and put your attention on the most relevant one. The Transformer's core part, attention, turns that action into computation. The smallest unit a model reads text in is called a token, roughly a word or half a word; attention has every token look over all the other tokens, give each one a score for "how relevant are you to me", and then mix their information in, weighted by those scores. To score, every token gets three vectors (lists of numbers): a query (what I am looking for), a key (what I can offer) and a value (the content I actually carry). The more one token's query resembles another token's key, the higher the score, and the more it takes from that token's value.

What problem it solves

Before it, the mainstream way to process text was the recurrent neural network (RNN): read one word after another, squeezing what you have read into a "memory" that gets passed along. This had two flaws. First, it had to compute in order, so the thousands of compute cores on a GPU could only wait in line, and training was slow. Second, in a long sentence, information from the start had been washed out by the time it reached the end. Attention lets every token see every token directly, which fixes both flaws at once: all positions can be computed at the same time, and however far apart two tokens are, it takes one step. Being parallel is what made it possible to make models and data very large, which is the precondition for the later "bigger is stronger" road (Pretraining and scaling).

What a Transformer looks like

It is the same kind of "block" stacked many layers deep. Each block does two things: first it does one round of attention, so tokens exchange information; then each token goes through a small fully connected network on its own, to digest the information it just got. Attention is usually done several times in parallel, called multi-head: each head can focus on a different relationship, say one on grammar and one on who a pronoun refers to. Two small design choices let it stack dozens or hundreds of layers without collapsing: residual connections, where each layer only "adds a small change" to its input instead of replacing it entirely; and layer normalization, which pulls each layer's values back into a stable range. Today's GPT-style models use only the "generating" half of the original paper's structure, called decoder-only, plus one rule called the causal mask: each token can only look at the ones before it, never peek at the ones after, because the model's job is to guess the next token (LLM: how the model works).

The cost

The cost of attention also comes from "every token looks at every token": double the sequence length and the number of scores to compute goes up four times (quadratic growth). Once the context gets long, both compute and GPU memory run short. Much of what you will meet later, the KV cache, long context, MoE, is haggling with this cost (Decoding and inference, Long context and MoE).

How to learn it

You need three things first: an intuition for matrix multiplication (Linear algebra; attention is a few matrix multiplications plus one softmax), backpropagation (Loss and backpropagation) and PyTorch: train a network yourself. After that, the best way to learn it is to write it yourself once: start from a minimal model that can only "guess the next character from the previous one", add attention, multiple heads and residuals step by step, and end with a small GPT that can continue text. Then go read the original paper, and you will find you recognize every sentence.

Builds on
Linear algebra · Loss and backpropagation · PyTorch: train a network yourself
Leads to
The third wave: scaling and LLMs · Long context and MoE · Multimodal · Parallel training: why one card is not enough · Pretraining and scaling
  • Let's build GPT: from scratch, in code, spelled out. free

    video · 2 hours + 4 hours coding — From a bigram model to multi-head attention and residual blocks in two hours; each line maps to a Transformer part. After it you can write GPT from scratch, the finish line for this layer.

  • nanoGPT free

    repo · one weekend — A 300-line minimal implementation that reproduces GPT-2 training. Reading it means understanding the pretraining loop; editing it is the cheapest ablation bench.

  • LLMs-from-scratch free

    repo · 7 chapters, 2–4 hours each — Code for Build a Large Language Model (From Scratch), a notebook per step: attention, GPT-2 weights, pretraining, finetuning. Karpathy gives intuition; this makes "build and train a GPT" a checklist.

Hands-on project: Write and train a GPT from scratch — Follow the video and hand-write a decoder-only Transformer. Train it on a small corpus until it can continue text. Then change one design choice (number of heads, position encoding, layer norm placement), run an ablation, and record the loss curve.

Not picked (4)
  • Jay Alammar「The Illustrated Transformer」(2018) — The best intro for reading diagrams, but it has no code. Finish Karpathy's video first, then come back to the diagrams to consolidate.
  • Vaswani 等「Attention Is All You Need」(2017) — The original paper; the entry is already in Attention Is All You Need. You can only follow it after you have written the code.
  • Harvard NLP「The Annotated Transformer」 — Annotates the original paper's implementation line by line, but it is encoder-decoder, which is far from today's decoder-only mainstream.
  • Stanford CS25 Transformers United — A lecture series. Good for building the full picture, not good as a first course.

Pretraining and scaling

transformertokenizerinformation-theorypretraining-and-scalingfine-tuning

Pretraining is the most expensive step in making a large model: take a Transformer whose parameters are all random numbers, and have it practice "guess the next token" over a vast amount of text, again and again, until it guesses accurately enough. The score for how accurately it guesses is called the loss: the higher the probability the model gives the correct answer, the lower the loss. Pretraining is adjusting the parameters step by step to push the loss down. The specific loss used here is called cross-entropy, which you can think of as "how surprised the model is when it sees the correct answer": the higher the probability it gave the correct answer, the less surprised it is.

Why does practicing only "guess the next word" teach it so much? Because to guess accurately, you have to understand a lot. To fill in "At standard atmospheric pressure, water heated to 100 °C will ____" correctly, you need some physics common sense; to guess the next line of a piece of code, you have to understand what the code before it is doing. Guessing the next token is an exam with no end, and the syllabus is the entire training corpus.

Data: where it comes from, how it is cleaned

The corpus comes mainly from web crawls, plus books, papers and code. Raw web pages are mostly junk: duplicate pages, ads, navigation bars, garbled text. So the bulk of data engineering is two jobs: deduplication (if the same passage appears thousands of times, the model memorizes it, and compute is wasted on it too) and filtering (using rules or small models to pick out high-quality text). For the same compute, a model with well-cleaned data is clearly stronger.

Scaling laws: bigger is stronger, and it is predictable

scaling laws are this node's most important finding: the more parameters a model has, the more data it is fed and the more compute is spent, the lower the loss, and it falls in a very regular way. Plotted on log axes it is almost a straight line (this kind of relationship is called a power law). That means you can first experiment on a series of small models, draw this line, and predict "if we spend ten times the money, where will the loss get to?", and only then decide whether to spend it. OpenAI's 2020 paper Scaling Laws for Neural Language Models was the first to draw these lines systematically.

In 2022, DeepMind's Training Compute-Optimal Large Language Models corrected one key piece of that accounting: for a fixed amount of compute, the parameter count and the amount of data should grow in proportion, at roughly 20 tokens per parameter. Before that, large models generally had "too many parameters, too little data". This conclusion rewrote the ratios of the models that followed. Its limit is that it only counts the training side: once a model is live it gets called billions of times, and the smaller the model, the cheaper each call, so many models today deliberately train a smaller model on far more data than this ratio suggests.

The training recipe

Besides data and scale, a few knobs decide whether a training run gets through smoothly:

  • Learning rate schedule: the learning rate is how much the parameters change at each step. It usually starts very small and slowly rises (called warmup), then gradually comes down; take big steps right from the start and training easily collapses.
  • batch size: how much text each step uses to work out "which way to change". The bigger it is, the steadier each step's direction, and the easier it is to split the work across many cards computing at once.
  • Mixed precision: do most of the computation with 16-bit or even lower-precision numbers, which saves memory and computes faster; keep 32 bits only where numerical errors creep in easily.

How it connects to other nodes

It turns the Transformer and the Tokenizer into a real model. The base model it produces can only continue text, and still has to be handed to Fine-tuning: teach it your task and Post-training: shaping with rewards to be trained into an assistant. How thousands of cards divide the work is L3's business (Parallel training: why one card is not enough); here we only get as far as "why so many cards": scaling laws tell you that more compute buys predictable progress, so everyone is willing to spend it.

Builds on
Transformer · Tokenizer · Information theory
Leads to
Fine-tuning: teach it your task
  • CS336: Language Modeling from Scratch free

    course · 19 × 80 minutes + assignments — Only public course that builds an LLM from scratch: tokenizer, architecture, MoE, GPU, parallelism, scaling laws, data, alignment. You implement each piece. It's your outline.

  • Training Compute-Optimal Large Language Models free

    paper · 2 hours — At fixed compute, scale parameters and data together, about 20 tokens per parameter. It rewrote every later training recipe. Read it to see why parameters held steady while data grew 10×.

Hands-on project: Draw a scaling curve on small models — Use nanoGPT to train three model sizes (each 4× apart in parameters) on the same corpus, each for the same number of tokens. Plot validation loss against parameter count on log axes. Then fix compute, vary the amount of data, and see whether Chinchilla's conclusion holds at toy scale.

Not picked (3)
  • Kaplan 等「Scaling Laws for Neural Language Models」(2020) — The first scaling paper, but its ratio of parameters to data was later corrected by Chinchilla; read that one first.
  • Stanford CS224n — Covers more ground (all of NLP), with only two lectures on pretraining; CS336 fits this node better.
  • Raschka「Build a Large Language Model (From Scratch)」ch. 5 — Its chapter on pretraining is very good, but the whole book is already a candidate for Transformer.

Fine-tuning: teach it your task

Who asks for it

pre-trained weightsfrozenLoRAtrainedyour examplesbetter atyour task

Fine-tuning means taking a model that is already trained and training it a little longer on examples you prepared yourself, so it gets better at one narrow job: an output format, a specialist domain, a tone of voice.

Here is an analogy. A pretrained model is like a new employee who has read the whole library and knows a little about everything; fine-tuning is showing them two hundred reports your company has written, so they learn to write in your format. What they hand in will look more like what you want, but they will not know much more as a result. The analogy marks the limit of fine-tuning: it mainly changes "how it answers", and it is hard to pour lots of new facts into a model this way. New facts are better retrieved at question time and handed to it (RAG: look up first, then answer).

SFT: the first step of post-training

The companies that build large models use the same technique. A base model fresh out of pretraining can only continue text (Pretraining and scaling), so it first gets a round of fine-tuning on a large number of "instruction → good answer" demonstrations. This is called SFT (supervised fine-tuning): "supervised" means every example comes with its correct answer. It teaches the model that "when someone asks a question, you give an answer", and what that answer should look like. After that, Post-training: shaping with rewards makes the answers better. So when you fine-tune, what you are doing is a scaled-down version of the first step of a big lab's post-training.

LoRA: fits on one card

Full fine-tuning changes all of the model's parameters, so GPU memory has to hold the parameters, the gradients and the optimizer state all at once, and for a large model that does not fit on one card (for why, see GPU basics: why it's used, and where the bottleneck is). LoRA (low-rank adaptation) freezes the original model and hangs a few very small extra matrices beside it; training changes only those small matrices. The parameters to train are often less than one percent of the original, and one GPU is enough. The extra module you end up with is small too, so you can swap modules in and out per task. The cost is that it can only change so much: when the task is far from what the original model is good at, it does worse than full fine-tuning.

When to use it, and how to prove it helps

Fine-tuning is the last resort, not the first move. The order is: first write a good prompt (Prompting: instructions you can measure), then add retrieval (RAG: look up first, then answer), and only when neither makes progress any more do you consider fine-tuning. That is because fine-tuning means preparing data, training, and maintaining a model of your own, and every time the base model is upgraded you may have to start over.

And it must have an eval (Evals: knowing whether it got better) proving that it beats a model that uses only a prompt: the same set of test questions, comparing quality, latency and the cost per thousand calls. Fine-tuning without this baseline comparison does not count: you don't know what your effort bought you.

Builds on
PyTorch: train a network yourself · Evals: knowing whether it got better · Pretraining and scaling
Leads to
Post-training: shaping with rewards
On the routes
Forward Deployed Engineer (Adapt the model) · AI Engineer (Measure and improve)
  • Hugging Face LLM Course free

    course · 3 chapters, about 20 hours — Tokenizers, the Trainer, and fine-tuning chapters in runnable notebooks — enough to fine-tune a small open model on your own data.

  • TRL documentation — Hugging Face free

    docs · 1–2 hours — The library behind most supervised fine-tuning and preference tuning (DPO, GRPO) you will be asked about, with working recipes.

Hands-on project: Fine-tune against a prompted baseline — LoRA-tune a small open model on one narrow task and compare it with a prompted frontier model on the same eval set — quality, latency and cost per 1,000 calls.

Not picked (3)
  • Ouyang 等「Training language models to follow instructions with human feedback」(InstructGPT, 2022) — The original source of the three-stage "SFT → reward model → reinforcement learning" recipe, but the RLHF book in Post-training: shaping with rewards already covers these ideas in full.
  • Hu 等「LoRA」(2021) — The original paper is short, but the TRL / PEFT docs have already turned it into a recipe you can follow step by step.
  • Unsloth 文档 — A tool that changes fast; not a good pick for explaining the principles.

Post-training: shaping with rewards

Who asks for it

ModelAnswer AAnswer BRewardA is bettertraining shifts it toward A

Reinforcement learning (RL) is a way of training that learns from "scores" rather than from "examples". SFT (Fine-tuning: teach it your task) shows the model the correct answers and has it learn by copying them; reinforcement learning has the model answer on its own, then a reward tells it how good the answer was, and training pushes it towards the higher scores.

Here is an example. When you learn chess, a teacher can tell you the right move at every turn (that is SFT), or tell you only whether you won or lost once the game is over (that is RL). The second gives you far less information, but it doesn't need anyone to know the right answer for every move, and you might even learn moves the teacher never thought of.

What problem it solves

SFT has a ceiling: the model can learn at most to be as good as the demonstrations. Yet often "writing the best answer" is hard, while "comparing two answers to see which is better" is much easier. Reinforcement learning takes advantage of exactly this. Rewards come from two kinds of places:

  • Human preferences: show people two answers to the same question and have them pick the better one. Once enough of these comparisons pile up, first train a reward model to imitate people's judgments, then use it to score each of the model's answers and do reinforcement learning. This whole setup is called RLHF (reinforcement learning from human feedback), and it is the key step that made assistants like ChatGPT useful (Training language models to follow instructions with human feedback). The later DPO (direct preference optimization) simplified it: no separate reward model and no reinforcement learning loop, just tuning the model directly on data about "which answer in this pair people preferred", which is simpler and more stable (Direct Preference Optimization: Your Language Model is Secretly a Reward Model).
  • Results that can be checked automatically: math problems have correct answers, and code can run unit tests. Have the model try many times, and reward it when it gets it right. That is how reasoning models learned to solve problems step by step: nobody demonstrated how to think; only the attempts that got the right answer in the end were rewarded (DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning).

There are several specific algorithms for turning a reward into parameter updates; the names you will see again and again are PPO and GRPO. Understand the ideas above first; the algorithm details can come later.

The cost: the model will game it

If a reward can be gamed, the model will learn to game it. This is called reward hacking. If the reward is "pass the unit tests", the model may learn to change the tests instead of fixing the code; if the reward model likes long answers, the model writes longer and longer. Human preferences have biases too: people like being agreed with, so the model learns sycophancy, telling users what they want to hear. To keep the model from drifting too far just to rack up points, training usually adds one more constraint: the new model's outputs must not differ too much from the model before training. Finding these loopholes and patching the reward is itself part of the job.

How it connects to other nodes

It follows the SFT in Fine-tuning: teach it your task, and together the two are called post-training, which is what people usually mean by alignment: making the model's behavior match what people intend. Once you understand it, you know where a model's "refusals", "sycophancy" and "rambling" come from: they are mostly shaped by rewards, not brought in by pretraining. In L4, Evals: knowing whether it got better and Security: the model acts on text it should not trust run into the same question again: is the score you are measuring what you really want?

Builds on
Fine-tuning: teach it your task
On the routes
AI Engineer (Train and post-train)
  • RLHF book — Nathan Lambert free

    book · about 12 hours — Post-training as practised on language models — reward models, PPO, DPO, verifiable rewards — by a researcher who post-trains open models, free to read online.

  • TRL documentation — Hugging Face free

    docs · an afternoon — Runnable GRPO and DPO trainers, so the book's methods become an experiment on a laptop-sized model.

Hands-on project: Preference- or reward-tune a small model on a verifiable task — GRPO on arithmetic or unit-test-checked code with a small open model; plot reward against a held-out eval and explain where it starts to game the reward.

Not picked (4)
  • Rafailov 等「Direct Preference Optimization」(2023) — The original DPO paper; the RLHF book has a chapter on it, so read the book first, then the paper.
  • Lilian Weng「Reinforcement Learning from Human Feedback」/ 早期 RL 系列 — High-quality survey, but the RLHF book is newer and more complete.
  • Sutton & Barto, Reinforcement Learning: An Introduction — The classic reinforcement learning textbook, but LLM post-training uses only a small corner of it; not worth reading the whole book.
  • Stanford CS336 对齐三讲 — Already in this layer through a candidate from Pretraining and scaling.

Decoding and inference

llmprobabilitydecoding-and-inferenceserving

At each step, a trained model gives you only a probability table: for every token in the vocabulary, how likely it is to come next (LLM: how the model works). Decoding is deciding how to pick one token from that table. Inference here means the act of "generating text with a trained model" itself, as opposed to training, and what it cares about is how fast and how cheaply you generate. Don't confuse it with reasoning (thinking step by step), as in "reasoning models".

Decoding: a few knobs

  • Greedy: at every step, pick the one with the highest probability. Simple and stable, but the writing is flat, and it easily falls into repetition.
  • Sampling: roll dice weighted by the probabilities. If a token has a 30% probability, it has a 30% chance of being picked. That is why answers vary: it is the reason you get a different answer when you click "regenerate".
  • Temperature: before rolling the dice, adjust how steep the probability table is. Turn the temperature down (close to 0) and the high ones get higher and the low ones lower, which is almost greedy: the answers are stable and conservative. Turn it up and the table flattens, so rare tokens get a chance too: the answers are more original, and also more likely to wander off topic.
  • top-k / top-p: cut off the long tail directly. top-k picks only among the k most likely tokens; top-p adds up probabilities from the highest down and stops once the total reaches p (say, 0.9), then picks only within that circle. The benefit is that tokens which are almost impossible, and which would send the sentence off course if picked, never get a chance.
  • beam search: keep several candidate sentences going at once, and at the end pick the one whose whole sentence has the highest probability. It approximately finds the sequence that is "most likely as a whole", rather than the most likely token at each step. It suits tasks with a standard answer, such as translation; it is rarely used in chat, because the most likely answer as a whole is often dull.

The temperature and top_p parameters you set in an API are exactly these knobs (Calling a model API: token, streaming, tools, cost).

Why inference is slow

A language model is autoregressive: each time it generates a token, it has to append it to the input and compute again before it can get the next one. Writing a hundred tokens takes a hundred passes, and those hundred passes can only run one after another, not in parallel. More importantly, every pass has to read all of the model's parameters out of GPU memory, and moving data is much slower than computing on it. The bottleneck is not the computing, it is the moving (GPU basics: why it's used, and where the bottleneck is). This is why you see the answer come out one word at a time.

Two remedies:

  • KV cache: in attention, each token's key and value (Transformer) never change once computed, so store them, and at the next step compute only the new token's share. This saves a large amount of repeated computation. The cost is GPU memory, and the longer the conversation, the more it takes.
  • Speculative decoding: first let a small, fast model draft several tokens in one go, then let the large model check them all at once; the right ones are accepted as they are, and from the first wrong one onwards the large model takes over. Checking several tokens takes the large model about as long as generating one, so the more the small model guesses right, the faster the whole thing gets, and the result is statistically the same as what the large model would have generated step by step on its own.

How it connects to other nodes

This node covers concepts only. Turning them into a system that serves hundreds or thousands of users at once (batching, quantization, scheduling) is L3's Serving: running models yourself. It uses words such as probability distribution and sampling from Probability and statistics, and it builds on LLM: how the model works. The best way to learn it is to skip the ready-made generate(), write a token-by-token loop yourself, add temperature, top-k and top-p one at a time, and watch how the output changes.

Builds on
LLM: how the model works · Probability and statistics
Leads to
Serving: running models yourself
  • Generation strategies — Transformers documentation free

    docs · 1 hour — Greedy, sampling, beam: what each is, which tasks fit, a runnable generate() call each; ends with a link to a top-k / top-p article. Run them: temperature and top_p become knobs, not nouns.

  • Fast Inference from Transformers via Speculative Decoding free

    paper · 1 hour — Small model drafts a few tokens, big model checks them in one pass: same output distribution, 2–3x faster. Shows decoding is memory-bound, not compute-bound; a top interview question.

Hands-on project: Write the sampling loop by hand — Take a small open-source model. Without generate(), write your own token-by-token loop that implements temperature, top-k and top-p. Then implement the simplest speculative decoding (small model drafts 4 tokens, big model verifies) and measure tokens per second for all three.

Not picked (3)
  • Hugging Face「How to generate text」博客 (2020) — The well-known post on top-k / top-p, but the docs page in the picks already links to it, and it lacks enough independent endorsement of its own.
  • Holtzman 等「The Curious Case of Neural Text Degeneration」(2019) — The original top-p paper; read it when you want to know why it beats top-k.
  • Lilian Weng「Large Transformer Model Inference Optimization」 — It covers engineering optimizations of inference systems, which belongs in L3.

Long context and MoE

transformerlong-context-and-moe

This section covers two modifications to the Transformer, and both are haggling with the Transformer's costs. Long context lets the model read a longer input in one go; MoE (mixture of experts) gives the model more parameters without the compute spent on each token going up with them.

Long context

The context window is the number of tokens the model can see at once: the prompt you write, the conversation so far and any files you paste in all have to fit inside it. The longer the window, the more easily it can read a whole book or a whole codebase in one go. Stretching it has two difficulties:

  • Can you afford the compute: attention has every token look at every token, so doubling the length quadruples the computation (Transformer). One remedy is sparse attention and sliding window attention: each token looks at only some of the tokens, for example only a stretch nearby.
  • Does it still know the positions: the model knows where each token sits in the order through positional encoding. A model trained only on shorter sequences does not recognize positions far beyond its training length. Today's mainstream choice is rotary position embedding (RoPE), which represents a position by "rotating the vector through an angle"; built on it, there are methods that let the model recognize positions further out than it saw during training. This is called extrapolation.

There is a third problem: fitting in is not the same as being used well. Research found that the model finds key information when it sits at the start or the end of a long input, but tends to overlook it in the middle. This is called lost in the middle. So "stuffing everything into the context" does not necessarily work better than retrieving only the few relevant passages and handing them to it (RAG: look up first, then answer).

MoE

Each layer of an ordinary Transformer contains a small fully connected network (FFN) that every token passes through. MoE replaces this network with several copies, each called an expert, and adds a router: as each token comes in, the router picks only a few of the experts to handle it.

Here is an analogy. A hospital has many departments; at the door, a triage desk sends each patient to one or two of them, instead of having every doctor see every patient. The hospital can keep many doctors (many parameters, room for more knowledge), while each patient takes the same amount of time (the compute per token stays the same). Where the analogy breaks down: the "experts" in a model do not divide the work by subject, like "math" or "history", the way departments do; the division they learn usually has no meaning a person can see.

So an MoE model has two parameter counts: total parameters (all the experts added up) and active parameters (the part each token actually uses). That is how a large model can hold more knowledge for about the same inference compute. There are two costs. All the experts have to sit in GPU memory, so the memory you need goes by total parameters, not active ones. And the router tends to play favorites, sending tokens to the same few experts again and again, so training adds an extra load balancing term to the loss to force it to spread the work evenly.

How it connects to other nodes

Both build on the Transformer. How MoE experts get spread across many cards in training, and how much GPU memory the KV cache for a long context eats at inference time, belong to L3 (Parallel training: why one card is not enough, Serving: running models yourself). As for how to learn it: swap MoE layers into a small GPT, then stretch its context, and watch with your own eyes how memory and speed change. That makes it clearer than any number of papers.

Builds on
Transformer
  • Mixtral of Experts free

    paper · 1 hour — Shortest paper that makes MoE clear: 8 experts per layer, 2 picked per token, 47B params but 13B compute. Explains why total and active parameters differ, and what MoE buys and costs (memory).

Hands-on project: Add an MoE layer to nanoGPT — Replace the FFN in the [[transformer]] project with 4 experts and top-2 routing, and add a load-balancing loss. Compare validation loss and memory use at the same compute. Then raise the context from 256 to 2048 and record how attention memory and speed change.

Not picked (4)
  • Hugging Face「Mixture of Experts Explained」(2023) — Friendlier to read, but its HN thread drew only 29 points, not enough independent endorsement; keep it as a companion when you read the Mixtral paper.
  • Fedus 等「Switch Transformers」(2021) — The founding MoE paper, and a long one; the Mixtral paper alone is enough to build the concept.
  • Su 等「RoFormer」(2021) — The original RoPE paper; read it when you change the positional encoding in the Transformer project.
  • Liu 等「Lost in the Middle」(2023) — The phenomenon matters, but its conclusion fits in one sentence you can remember.

Multimodal

transformerclassic-architecturesmultimodal

A multimodal model is one that can handle images, sound and video as well as text. When you drop a screenshot of an error into a chatbot and ask "what does this mean?" and it understands, that is multimodality at work.

There is only one key idea: a language model only accepts sequences of tokens, so find a way to turn an image into a sequence of "token-like things" too. There are two mainstream ways to connect them:

  • Feed it into the sequence as tokens: a modality encoder cuts the image into small patches and turns each patch into a list of numbers (a vector), then a small projection layer translates those into a format the language model can read, and they sit in the same sequence as the text tokens. The language model processes them as usual, as if the image were a "foreign language" it can read. LLaVA is the representative of this route.
  • Plug it in from the side: the text goes through the language model as usual; the image's vectors are brought in at some of the middle layers through cross-attention. In those layers, besides looking at each other, the text tokens also "look at" the image. DeepMind's Flamingo is the representative of this route.

Where the encoder comes from

Both routes need a pretrained encoder, and for images a model in the style of Learning Transferable Visual Models From Natural Language Supervision is common. CLIP is trained on huge numbers of "image + caption" pairs: it pulls the vectors of matching images and texts closer together and pushes non-matching ones apart, a kind of training called contrastive learning. Once trained, the image vectors it gives naturally line up with the meaning of text, which saves most of the effort when you connect it to a language model. The half of it that looks at images is often a ViT itself (cut the image into patches and feed them to a Transformer as tokens), but it can also be an older convolutional network (Classic architectures: CNN, RNN / LSTM, residuals).

Alignment training

The encoder and the language model were trained separately, and each speaks its own "language". Once they are connected, there is a stage of alignment training: image–text pairs teach the projection layer (sometimes together with the language model) to translate image vectors into places the language model can understand. After that comes a round of instruction fine-tuning on "image + instruction + answer" data, which is exactly the SFT from Fine-tuning: teach it your task, only in image-and-text form.

Why you need to understand the structure

Once you understand these two routes, you can answer "how is a multimodal model different from a text-only one" from its structure, instead of just saying "it can see images". For example: how many tokens an image takes up (which directly sets the cost and how much context is left); why the model often gets it wrong when reading small text in an image or counting things in it (one common reason is that the image was cut into patches and squeezed into a limited number of vectors, and the details were lost). It builds on the Transformer.

Builds on
Transformer · Classic architectures: CNN, RNN / LSTM, residuals
  • Visual Instruction Tuning free

    paper · 1.5 hours — Original simplest multimodal LLM recipe: a projection layer turns patch features into image tokens for the LM, then instruction tuning. You can then explain how a model sees in three sentences.

Hands-on project: Attach a vision encoder to a small language model — Use an off-the-shelf CLIP vision encoder and an open-source language model under 1B parameters. Train only a linear projection layer on a small image-text dataset for image captioning. Record what it gets right and wrong, and explain what the projection layer is aligning.

Not picked (3)
  • Raschka「Understanding Multimodal LLMs」(2024) — The survey that compares the two ways of connecting most clearly, but it lacks independent endorsement (4 points on HN); strongly recommended as a companion after LLaVA.
  • Radford 等 CLIP 论文 (2021) — Where the vision encoder comes from, and very widely cited, but it is about contrastive learning, not multimodal LLMs themselves; read it when you need it.
  • Chip Huyen「Multimodality and Large Multimodal Models」(2023) — Likewise lacks endorsement, and its content overlaps with Raschka's article.

Self-check

  • Without references, I can write the forward pass of a decoder-only Transformer (embeddings, positional encoding, multi-head causal attention, FFN (the small fully connected network each token passes through on its own), residuals and normalization), and train it on a small corpus until it can continue text. (Hint: the "forward pass" is the one computation that goes from the input tokens all the way to the output probability table.)
  • I can explain why attention scores are divided by √d, why the causal mask is needed, and what difference it makes whether layer normalization goes before or after a sublayer. (Hint: d is the length of the query and key vectors; if the scores get too large, softmax becomes extremely peaked and almost stops learning.)
  • I can talk through the whole pipeline, pretraining → SFT → RLHF / DPO, and for each step say what it changes in the model and what data it uses. (Hint: the three steps use, in turn, huge amounts of web text, demonstration Q&A pairs, and people's preferences between two answers.)
  • I can state Chinchilla's conclusion and why it rewrote the balance of parameter count and data in the models that followed. (Hint: with compute fixed, how should the two grow together?)
  • I can explain what temperature, top-p and speculative decoding each do, and why an MoE's "total parameters" and "active parameters" are two different numbers. (Hint: in an MoE each token passes through only a few experts.)

Hands-on projectWrite a GPT from scratch and train it on a small corpus until it can keep going from an opening you give it. Then change one design choice (the number of attention heads, the kind of positional encoding, or where layer normalization goes), retrain, and run an **ablation** (change exactly one thing and see how much the result differs), plotting the two loss curves together. When you're done you'll have watched the loss come down step by step, and you'll know what one design choice is actually worth (attached to Transformer).

Spot a mistake on this page?