Models learn by guessing, checking and adjusting. So can you: change the numbers in a live toy and see how language models are trained, adapted and served.
PredictEach bench first asks you to guess what will happen. Guessing first makes the toy stick.
PlayEach bench has a live toy on a tiny language model. Move the sliders.
RememberThe red box is the common mistake, the teal box the essential takeaway.
Look up“Terms on this bench” spells out every abbreviation, with pictures and links. Plain mode swaps in plain analogies.
Choose your track
Start here
The basics
Basics 1
A model is a function made of numbers
Every model, from a spam filter to GPT, is built from one small unit: multiply each input by a weight, add them up, squash the result. An LLM is billions of these.
Plain modeA neuron is a tiny judge. It listens to a few clues, trusts some clues more than others, adds it all up and says “yes” or “no”. A big AI is millions of tiny judges passing notes to each other.
Key ideaThe weights decide how much each input counts. Training is nothing more than finding good weights. “8B model” means 8 billion weights.
Predict first
You set the weight for links to 0. The email now has 10 links instead of 3. What happens to the spam score?
A weight of 0 multiplies its input by 0: the number of links no longer counts at all.
Live toy · one neuron decides: is this email spam?
3
yes
0.6
1.5
-3.0
Weighted sum
0
After squashing
0
Verdict
–
TrySet the weight for links to 0: the number of links no longer matters at all. Make the “FREE” weight negative and the word now argues against spam. Choosing these numbers by hand is impossible for billions of weights, so the next bench lets the computer find them.
Common mistakeThinking a neuron “understands” its inputs. It only multiplies, adds and squashes; any meaning comes from weights learned on data.
Essential takeawayA neural network is layers of these units. Each takes numbers in, multiplies them by its weights, adds a bias and passes the squashed result on. Everything the model “knows” is stored in those weights.
Training means nudging weights until the error is small
The simplest possible model, a straight line with two weights, learns from data in exactly the same loop an LLM uses: guess, measure the error, nudge, repeat.
Plain modeIt is like tuning a guitar string. Play it, hear how far off it is, turn the peg a little, play again. Turn too hard and you overshoot; turn gently and you get there.
Key ideaThe model measures how wrong it is (the error), works out which way each weight should move to make the error smaller (the gradient) and takes a small step. Thousands of steps later, the weights fit the data.
Predict first
What happens if you make the learning rate much bigger?
Each step jumps past the best line by more than the last one, so the error grows instead of shrinking. That is divergence.
Live toy · fit a line to hours studied vs test score
0.010
Step
0
Line
–
Error (MSE)
–
TryPress Train and watch the dark error lines shrink. Reset, set the learning rate to 0.03 and train again: the steps are too big and the line flies off (divergence). At 0.002 it gets there, but slowly.
Common mistakeJudging training by a single step. The error falls over many small steps; one bumpy step is fine, a steady rise is not.
Essential takeawayTraining repeats one loop: predict, measure the error with a loss function, compute the gradient, step every weight a little against it. An LLM does the same thing with billions of weights and a different loss.
Tokens are not words, and languages pay differently
Context windows, latency and API price are all counted in tokens. German and Italian cost more than English.
Plain modeThe AI reads text in Lego bricks, not in whole words. Short common words are one brick, long German words need many bricks. More bricks means more work and a bigger bill.
Why it mattersFor German, Italian or Russian text the same document fills more of the context window and costs more than an English demo suggests, and how much more depends on the tokenizer.
Predict first
The same contract in English and in German, with GPT-4’s tokenizer. Which needs more tokens?
Measured on the same email: 1.11 tokens per word in English, 1.83 in German, 65% more. GPT-4o’s larger multilingual vocabulary narrows the gap to 25%.
Live toy · how one sentence is cut by two real tokenizers
Real splits from OpenAI’s open tokenizers, measured with js-tiktoken. Llama, Mistral and Qwen use their own vocabularies built the same way (BPE).
Words
0
Tokens
0
Tokens per word
0
Live toy · does the client’s document fit?
120
Estimated tokens
0
Share of window
0
Verdict
–
Tokens per word, measured on one sample: the same 107-word customer-service email translated into each language. Other texts give other ratios (code, names and numbers change them a lot), so treat these as an example, not a constant. GPT-4’s cl100k: 1.11 English, 1.83 German, 1.85 Italian, 3.01 Russian. GPT-4o’s o200k: 1.11, 1.39, 1.64, 1.66. Assumes 500 words per page.
Live toy · count your own text with a real tokenizer
The first count downloads the tokenizer (about 1–2 MB) from the jsDelivr CDN.
TryKeep 120 pages with the English-centric tokenizer: English fits a 128k window with room to spare, German barely fits, Russian overflows. Switch to the multilingual tokenizer and Russian fits again: same text, different tokenizer. When it does not fit, that is a RAG decision, not a prompt tweak.
Common mistakeEstimating context and cost from word counts with an English rule of thumb. Measure with the model’s own tokenizer, per language.
Essential takeawayTokens, not words, drive context, latency and price. In our one sample email, German needed 65% more tokens than English with GPT-4’s tokenizer and 25% more with GPT-4o’s; your texts will differ. Size context windows and budgets per language and per model, and measure on your own texts with the model’s own tokenizer.
There is no plan for the whole answer. The model scores every possible next token, one is picked, it is added to the text, and the model runs again.
Plain modeIt is the game where everyone adds one word to a story. The AI looks at the story so far, thinks about which words could come next, picks one, and passes the story back to itself.
Key ideaEach step gives a probability for every token. Temperature makes the choice bolder or safer, then top-p cuts off the unlikely tokens from what temperature left, and the picked token becomes part of the input for the next step. Because temperature comes first, it changes what top-p cuts.
Predict first
At temperature 0.2, how often will the model pick the rare word “purple”?
Low temperature sharpens the distribution: likely tokens get even likelier and rare ones nearly vanish.
Live toy · a tiny model continues a sentence
1.0
1.00
Reading the prompt happens in one go (prefill). Writing happens one token per run of the model (decode), which is why long answers take longer than long questions.
TryRestart and press “Pick most likely” a few times: always the same sentence. Then set temperature to 1.8 and pick randomly: “purple” starts to appear. Set top-p to 0.6: the unlikely words are cut off and greyed out. Now raise the temperature: the chances flatten, so top-p needs more words to reach 60% and keeps more of them. Temperature is applied first, so the two settings interact.
Common mistakeExpecting identical answers everywhere at temperature 0. Greedy decoding repeats on one setup, but batching and different hardware can still change outputs slightly.
Essential takeawayAn LLM is a next-token predictor run in a loop. Each step outputs a probability for every token in its vocabulary; a sampling rule (greedy, temperature, top-p) picks one, and the text so far is fed back in.
Inside a transformer: one block, stacked many times
Every modern LLM has the same skeleton. Click each part to see what it does and how big it is in an 8B model.
Plain modeThink of a factory line. Words come in at the bottom, each floor does the same two jobs (talk to the other words, then think alone), and after 32 floors a guess for the next word comes out at the top.
Key ideaEach block does two jobs: attention lets words share information, the MLP lets each word think on its own. The block repeats 32 times in an 8B model, then the last layer turns the result into next-token scores.
Predict first
In an 8B model, which part holds the most weights?
The MLP: about 5.6 B of 8.0 B weights, roughly 70% of the model and 81% of every block. Attention holds about 1.3 B; the embedding table and LM head about 0.5 B each.
Live map · click a part, or step through
× 32 blocks
Where the parameters live · Llama-3-style 8B, 32 layers, hidden size 4096
Per layer: attention projections 41.9 M (queries and outputs 4096×4096, keys and values 4096×1024 thanks to GQA), MLP 176.2 M (three 4096×14336 matrices), so the MLP is 81% of each block. Vocabulary of 128,256 tokens for the embedding table and the LM head. Every one of these numbers is a parameter.
TryStep from the bottom to the top. The two big parts, attention and the MLP, hold almost all the weights: the MLP is 81% of each block and about 70% of the whole 8B model, because the embedding table and the LM head take about 1 B between them.
Common mistakeBelieving the knowledge sits in attention. Attention moves information between words; most stored facts and patterns live in the MLP weights.
Essential takeawayA decoder-only transformer is token embeddings, then a stack of identical blocks (attention, then MLP, each with a residual connection and normalisation), then an LM head and softmax. The whole stack runs once for every new token. In an 8B model about 70% of the parameters sit in the MLPs.
Where do pre-training, fine-tuning, LoRA, RL, quantization and serving fit? In six stages, and only the last three are usually yours. One running example follows the model through all of them: “Reply to customer: Your order ___”.
Plain modeFirst the AI reads a giant library (school). Then it practises answering questions (homework). Then people tell it which answers are nicer (a coach). Then you teach it your special topic, shrink it so it fits, and let it answer questions all day.
Key ideaLabs spend millions on stages 1–3 to make a model that follows instructions. Most projects only touch stages 4–6: adapt it to your data, make it smaller and faster, and serve it.
Predict first
Which stages do most company projects actually change?
Stages 1–3 cost millions and are done by model labs. Projects adapt an existing model with prompting, RAG or LoRA, then compress and serve it.
Live map · click a stage
Common mistakePlanning a project as “we train our own model”. Almost always you adapt an existing model, and the first question is which lever to pull: see Where to choose what.
Essential takeawayPre-training on trillions of tokens gives a base model; instruction tuning (SFT), preference tuning (RLHF or DPO) and RL with verifiable rewards turn it into an assistant. You then adapt it with prompting, RAG or LoRA, compress it with quantization or distillation, and serve it with an inference engine.
Part one
How a model learns
Learning 1 · Loss
Loss punishes doubt, and punishes confident mistakes far more
Two models can both be “right” and still deserve very different scores. Loss sees that, accuracy does not. And a model that is sure of the wrong answer pays the most of all.
Plain modeTwo kids both give the right answer. One is sure, the other just guessed. Loss gives the sure kid the better score. Accuracy only says right or wrong.
Key ideaLoss is a formula giving one number per example. For an LLM it is cross-entropy, −ln p of the correct token. The plot over steps is the loss curve.
Predict first
Model A gives the right word 45%, model B 95%. Both pick the right word. Which has the lower loss?
Loss is −ln p of the correct word: 0.80 for A, 0.05 for B. Accuracy calls both 100%. The asymmetry matters more: a model that gives the correct word only 1% (because it is sure of another word) pays 4.6, almost six times A’s loss.
Live toy · “The cat sat on the mat”, correct token “mat”
45%
Cross-entropy loss
0
Perplexity
0
Accuracy (top-1)
0
TryCompare models A and B. Both guess right, so accuracy is 100% for both. Their loss differs about 15×. Training follows loss because it has a smooth gradient.
Common mistakeReporting only accuracy during training. Accuracy can stay flat while the loss improves a lot, and loss is what training optimises.
Essential takeaway“We optimise cross-entropy because it is differentiable and rewards calibrated confidence; accuracy is for reporting. Perplexity is just e to the power of the loss.”
Learning 2 · Training loop
Backprop computes gradients, the optimizer changes weights
Four steps, four different actors. Step through them and watch the matching line of PyTorch light up.
Plain modeAfter a wrong answer the AI asks each of its parts “how much was this your fault?”, starting from the end. That is backprop. Then the optimizer gives each part a small nudge to do better next time.
Key ideaFirst only the loss exists. Backprop walks from output to the first layer and computes gradients. Then the optimizer steps: w ← w − lr·g.
Predict first
Right after loss.backward(), have the weights changed?
backward() only computes gradients. The weights change in optimizer.step().
Live toy · one training step, four layers
Step
0 of 4
Who does it
–
Loss
–
for batch in loader: logits = model(batch.input_ids) # 1 forward pass loss = F.cross_entropy(logits, batch.labels) # 2 loss loss.backward() # 3 backprop: gradients optimizer.step() # 4 update weights optimizer.zero_grad() # clear for next batch
TryGo round the loop twice. The second time loss is lower and gradients are weaker: the model is closer to the bottom.
Common mistakeForgetting optimizer.zero_grad(). PyTorch adds new gradients to old ones, so every step would use a growing, wrong gradient.
Essential takeaway“Forward pass, then loss, then loss.backward() computes every gradient with the chain rule, optimizer.step() updates the weights, and zero_grad() clears the gradients for the next batch.”
Learning 3 · Weights in action
Change a weight, get a new prediction
A prediction is arithmetic on weights. Here the last layer of a tiny model is small enough to see whole: change one number and watch the next-token guess move, then let one training step change all of them.
Plain modeThink of a mixing desk with 16 sliders. Each slider sets how loud one input is in one output channel. Push one slider and one word gets louder. Training is a sound engineer who nudges every slider a little after each song.
Key ideaEach candidate word has a row of weights. Its score (logit) is that row multiplied by the context’s numbers, added up. Softmax turns the scores into probabilities. A training step moves every weight by −lr × gradient, and here the gradient is simply (predicted probability − target) × input.
Predict first
You raise one weight in the row for “is”. What happens to the probability of “has”?
Probabilities must add up to 100%. When the score for “is” rises, softmax gives “is” a bigger share and every other word, including “has”, loses some, even though their weights did not change.
Live toy · the last layer of a tiny model, “Reply to customer: Your order ___”
Context numbers x
made by the layers below from “Your order”
×
Weights W · click a cell
=
Score → probability
0
Training steps
0
p(word to teach)
0
Loss −ln p
0
TryClick the cell where row “is” meets x₂ and drag the slider up: “is” overtakes “has”, and every other bar shrinks. Press Reset, keep “is” as the word to teach and press “One training step”: the arrows show that the whole “is” row moved and the other rows moved the opposite way, each by an amount proportional to its input. After about 20 steps the model says “is on its way”.
Common mistakePicturing one weight per fact. Every prediction uses many weights, and every weight takes part in many predictions; one training step changes all of them a little.
Essential takeawayA prediction is weights times inputs, turned into probabilities by softmax. Training changes each weight by −lr × (probability − target) × input: weights that would have helped the right word go up, the others go down. Billions of such small, shared changes are what “learning” means in an LLM.
A real training loop on five candidate tokens. Change the step size and the batch and watch it learn, crawl or thrash.
Plain modeLearning rate is the size of your steps when you walk to a treasure with your eyes closed. Giant steps: you keep jumping past it. Tiny steps: you get there, but it takes forever. Try the sliders and watch.
Key ideaNot getting stuck is true, but the main risk is different: loss jumps or explodes, called divergence. In fine-tuning it also causes catastrophic forgetting.
Predict first
Batch size 1 and learning rate 15. What will the probabilities do?
Each batch of one sentence pulls hard toward its single word; the next batch pulls somewhere else. Big steps plus noisy batches thrash.
Live toy · learning “The cat sat on the ___” from 64 sentences
Green bar: the model’s probability. Dark tick: frequency in the data.
1.0
8
Loss
–
Step · epoch
0 · 0
Still to learn (loss − entropy)
–
Current batch
Why the loss stops at a floor · entropy
Entropy measures how unpredictable the next word really is in the data. If the data always says “mat”, a model can be 100% sure and reach loss 0. If the data itself is split between several words, even a perfect model has to spread its bets, so some loss always remains.
Entropy, in bits
0
Entropy, in nats (the loss floor)
0
Like choosing between
0
Formula: entropy = − Σ p × log p over all words. The loss a model gets is the entropy of the data plus a penalty for every way its own probabilities differ from the data’s. Training can remove the penalty, never the entropy. “Like choosing between” is perplexity: the number of equally likely words with the same uncertainty.
Why AdamW and not plain SGD? SGD moves every weight by the same learning rate times its gradient. Adam keeps a running mean of each weight’s gradient (momentum) and of its squared size, and divides by the second, so weights with small, noisy gradients still move and large ones do not jump. That makes transformers train with far less tuning; the price is two extra numbers per weight (the 8 bytes of optimizer state on the GPU bench). AdamW applies weight decay separately from that scaling.
TryBatch 1 and learning rate 15: probabilities thrash. Batch 64 and rate 1: smooth, one epoch equals one step. Rate 0.1: it learns, slowly.
Common mistakeCopying a pre-training learning rate into a fine-tune. Full fine-tuning needs a lower peak (about 1e-5 to 2e-5), and LoRA about 10 times the full fine-tuning rate.
Essential takeaway“Too high a learning rate diverges, too low wastes compute. I use warmup plus cosine decay, a lower peak for fine-tuning, and when I raise the batch size I usually raise the learning rate with it.”
Learning 5 · Generalization
Overfitting shows on two loss curves
Memorising the training set looks like progress on one curve and like decline on the other.
Plain modeIf you learn the answers of one practice test by heart, you ace that test and fail a new one. Overfitting is learning by heart instead of understanding. The dark line shows the new test.
Key ideaBy two losses, training and validation. Training keeps falling while validation turns upward. The validation minimum is the moment for early stopping.
Predict first
With only 500 examples and no dropout, when does validation loss start to rise?
A small dataset is memorised quickly: training loss keeps falling while validation turns up after a few epochs.
Live toy · a fine-tune over 30 epochs
12
Training loss
0
Validation loss
0
Best checkpoint
0
Try500 examples without dropout: the gap opens at epoch 5. Turn dropout on: the turn comes later and softer. 50,000 examples: almost no overfitting, which is why pre-training often runs without dropout.
Common mistakeKeeping the last checkpoint. The best model is the one at the validation minimum, which may be many epochs earlier.
Essential takeaway“I watch training and validation loss together. When validation turns up I stop and keep the best checkpoint. Dropout, weight decay and more data push that point later.”
Part two
Inside the transformer
Transformer 1 · Attention
Attention: each token picks whom to listen to
Expect “explain attention” and “why is long context expensive” in almost every LLM design discussion.
Plain modeIn “The bank refused the loan because it was too risky”, what does “it” mean? You look back at the other words and decide: the loan. Attention is the AI looking back at earlier words to see which ones matter. Click the words!
Why it mattersAttention is how a token gathers meaning from earlier tokens. Its cost is the main reason long context is slow and memory-hungry.
Predict first
Double the context from 64k to 128k tokens. How many attention scores does each head compute?
Each token scores every earlier token: about n² ÷ 2 scores, so compute quadruples. With FlashAttention, score memory does not quadruple, and the KV cache only doubles.
Live toy · click a token to make it the query
8k
Scores computed per head per layer
0
Compared with 2k
×1
Faded tokens are hidden by the causal mask: a token never sees what comes after it. The score count is compute, and it grows with the square of the context. FlashAttention computes the scores in tiles and never stores the whole table, so memory for scores does not grow quadratically; in serving, the memory that grows is the KV cache, linearly with tokens.
Why does a word need a query?
Think of a library search. To work out its meaning, every word makes three things:
Querywhat this word is looking for“it”: which earlier thing am I talking about?
Keythe label each word shows to others“loan”: a thing that can be risky · “bank”: a company
Valuewhat a word hands over once it is picked“loan” passes on its meaning, so “it” now means the loan
The query is separate from the word itself because what a word needs is different from what it is. “it” is not a loan, but it is searching for one. Each query is scored against every key; the best fits pass their values on. Each head asks its own question, which is why head 2 finds neighbours instead.
How are queries, keys and values learned?
A word does not store them. They are made on the fly: the word’s 4,096 numbers are multiplied by three weight tables, WQ, WK and WV, one set for every head in every layer. These tables are ordinary weights. Nobody tells them to look for nouns. During training, whenever paying attention to a word helped predict the next token, backprop nudges WQ and WK so that the query and key match better, and WV so that the value carries what helped. The labels in the cards above are how people describe what trained heads end up doing.
0%
Attention from “it” to the earlier words. Later the model has to predict “risky” after “it was too”, which is easier when “it” has picked up the meaning of “loan”.
Attention from “it” to “loan”
0
p(“risky” comes later)
0
Loss for that word
0
TryClick “it” in head 1: it looks at “loan”, not “bank”. In head 2 the same token looks at its neighbours, which is multi-head attention. Then double the context and watch the score count quadruple.
Common mistakeConcluding that long context needs quadratic memory. With FlashAttention the score table is never stored; the memory that grows is the KV cache, and it grows linearly.
Essential takeawayEach token’s query is scored against the keys of all earlier tokens; the scores go through softmax and mix the values. Compute grows with the square of sequence length. Memory does not have to: FlashAttention never stores the full score table, and the KV cache that serving keeps grows linearly with tokens.
Positional encodings: RoPE turns position into rotation
Attention alone is order-blind. Two toys: first see the problem, then see how RoPE solves it.
Plain mode“Dog bites man” and “man bites dog” use the same three words, but they tell very different stories. The AI needs a seat number for every word so it knows the order.
Why it mattersMost current open LLMs (Llama, Mistral, Qwen) use RoPE, and context extension tricks work by changing it.
Predict first
Add three words in front of the sentence. What happens to the angle between the hands of “cat” and “mat”?
Every hand turns by the same amount, so the angle between any two words depends only on how far apart they are.
Live toy · order-blind without positions
Live toy · every word gets a clock hand
Each word holds a clock hand. One seat further right turns the hand 30° further.
Click two words. Attention compares their hands: the smaller the angle between them, the better the match.
Add words in front. Every hand turns, but the angle between your two words stays the same.
Seats apart
0
Angle between hands
0
Match (simplified)
0
Real models give each word many such clocks, each turning at its own speed, so both short and long distances can be told apart. This toy shows one clock.
TryKeep “cat” and “mat” picked and note the angle. Press “Add a word in front” three times: every hand moves, but the angle and the match do not. With RoPE, attention depends on how far apart two words are, not on where the sentence starts.
Common mistakeAssuming a model trained on 8k tokens works at 128k. Beyond the trained length RoPE produces angles the model never saw; context extension such as YaRN plus training on long texts is needed.
Essential takeawayAttention alone does not know word order, so the model must be told where each word sits. RoPE gives every word a clock hand turned by its seat number, so two words compare only how far apart they are. Today’s largest models read up to about a million tokens at once; to get there, engineers slow these clocks down (one method is called YaRN) and train briefly on long texts.
Transformer 3 · Mixture of experts · deep dive
Mixture of experts: many MLPs, only a few run per token
Most large open-weight models of 2025–26 replace the single MLP in each block with many smaller “experts” and a router that picks a few of them for every token.
Plain modeA clinic has 8 specialists, but each patient sees only the 2 who fit best. The clinic pays rent for all 8 rooms (memory), but each visit costs only 2 doctors’ time (speed).
Key ideaMemory depends on total parameters: every expert must sit in GPU memory, because any token may need it. Speed and compute per token depend on active parameters: only the chosen experts run.
Predict first
A 30B-parameter MoE model uses 3B parameters per token. Compared with a dense 3B model, how much GPU memory do its weights need?
All 30B weights must be loaded, because the router can send the next token to any expert. Only the compute per token is like a 3B model.
Live toy · the router sends each token to the top experts
Reply to customer: “Your order ships Thursday, tracking 4471.”
2
Labels show what each expert handles most often in this toy. In real models the split is messier: experts specialise on token types and patterns more than on clean topics.
Live toy · total versus active parameters in four real models
active for one tokenloaded but idle for this token
Total parameters
0
Active per token
0
Weights in INT4
0
Experts per token
0
TryClick each token: punctuation, numbers and verbs go to different experts. Raise top-k to 4: more experts run, so compute per token doubles. Then compare the four real models: DeepSeek-V3 keeps 671 B parameters in memory but runs only 37 B per token.
Common mistakeSizing the GPU by active parameters. A “30B-A3B” model needs memory for all 30 B weights plus the KV cache, even though it runs about as fast as a dense 3B model.
Essential takeawayA mixture-of-experts layer swaps one MLP for many experts and a learned router that sends each token to the top few. Memory follows total parameters; speed and cost per token follow active parameters. Training adds a load-balancing term so the router does not overuse a few experts.
Evaluation: can you actually tell two models apart?
Every decision on this page is only as good as the eval set behind it. Small test sets, leaked questions and biased judges all produce confident wrong conclusions.
Plain modeFlip a fair coin 10 times and you may well get 7 heads. A test with 50 questions is a bit like that: a few lucky answers can make one model look better than another when it is not.
Key ideaA score is an estimate with a confidence interval. At 70% accuracy, 50 questions give about ±13 points, so 70% and 75% cannot be told apart. Compare on the same questions (paired), keep a private held-out set against contamination, and check your LLM judge against human labels.
Predict first
Your customer-reply model scores 70% on 50 test questions; the new version scores 75%. Is the new one better?
With 50 questions each score is uncertain by about ±13 points. The two intervals overlap almost completely; you would need roughly 1,300 questions per model to trust a 5-point gap.
Live toy · two versions of the customer-reply model
95% interval, A
–
Verdict
–
Questions needed for this gap
–
Wilson 95% intervals; the verdict is a two-sided test at the 5% level that treats the scores as independent, and “questions needed” is for 80% power. Scoring both models on the same questions and comparing them question by question usually needs fewer.
Contamination
LLM-judge bias, two equally good answers
Numbers in these two panels are illustrative. The patterns are well documented: scores inflate on leaked questions, and judges favour the first answer and the longer one.
TryKeep 70% against 75% and raise the questions from 50 to 1,500: the intervals separate and the verdict flips. Then leak the benchmark: the score on the original questions jumps, the score on reworded copies does not. In the judge panel, swap the order and turn on the longer answer.
Common mistakeDeclaring a winner from a 3-point gap on 50 questions, or from an LLM judge nobody checked. Report the interval, swap the answer order, and hand-label a sample to measure how often the judge agrees with people.
Essential takeawayAn eval score is a measurement with error bars: at 70% on 50 questions, about ±13 points. Use hundreds of questions, compare models question by question, keep a private set that never touches training, and treat an LLM judge as an instrument that needs calibration: swap the order, control for length, check it against human labels.
Pre-training: compute, tokens and the data behind them
Before any fine-tuning, a lab trains the base model on trillions of tokens. One formula sizes the compute; data work decides the quality. This is where “Your order has been shipped” first comes from: millions of shipping emails on the web.
Plain modePre-training is a giant reading marathon. A bigger brain and more books mean a longer marathon. Reading the same bad book twice teaches nothing, so most of the work is choosing the books.
Key ideaTraining compute ≈ 6 × N × D FLOPs, with N parameters and D training tokens. Compute-optimal training (Chinchilla, 2022) uses about 20 tokens per parameter, but current models are deliberately over-trained far beyond that: a smaller model costs more to train and less to serve, every day, for years.
Predict first
Llama 3 8B was trained on about 15 trillion tokens. How many tokens per parameter is that?
15 trillion ÷ 8 billion ≈ 1,875 tokens per parameter, about 90 times the Chinchilla ratio. The extra training buys a stronger small model, which is cheaper at inference.
Live toy · how much compute does a pre-training run need?
Compute 6·N·D
–
H100 GPU-hours
–
Wall-clock time
–
Tokens per parameter
–
Assumes 989 TFLOPS per H100 (dense BF16) times the MFU you set. Real runs land within a factor of 2–3 of this because of restarts, evaluations, data loading and communication.
Why over-train? Training is paid once, serving every day
Two models with about the same MMLU score (≈67%, 5-shot) and similar training compute: Chinchilla 70B on 1.4 T tokens (2022) and Llama 3 8B on 15 T tokens (2024). Serving costs about 2 × N FLOPs per generated token.
Live map · from raw web to training data, click a stage
TryPress “Llama 3 8B”: about 7 × 10²³ FLOPs. At 40% MFU that is about 0.5 M H100-hours; Meta reported 1.3 M, inside the factor of 2–3. Then press “Qwen3-0.6B”: 36 T tokens for 0.6 B parameters, 60,000 tokens per parameter. In the second toy, raise the daily volume until the small, over-trained model is clearly cheaper overall.
Common mistakeReading Chinchilla’s 20 tokens per parameter as “the right amount of data”. It is the cheapest way to reach a loss with a given training budget, not the best model for a given serving budget. That is why today’s small models train on thousands of tokens per parameter.
Essential takeawayPre-training costs about 6 × N × D FLOPs. Chinchilla-optimal is about 20 tokens per parameter, but models that will be served a lot are over-trained, because inference costs about 2 × N per token forever. Quality comes mostly from the data pipeline: deduplication, filtering, the data mix, a mid-training phase on the best data, and verified synthetic data.
LoRA adds a correction, it does not replace weights
SFT trains a model on prompt and answer pairs. LoRA is the cheap way to do it: the base model stays untouched, and a small trainable add-on bends its answers toward the client’s style.
Plain modeImagine a big recipe book you are not allowed to write in. You stick a small note on a page: “add a bit more sugar”. The book stays the same, but the cake tastes different. LoRA is that sticky note for an AI.
Key ideaThe big weight table W is frozen. Two thin tables, B and A, are trained instead. Multiplying them gives a full-size correction, which is scaled and added: used weights = W + (α / r) × (B × A). Libraries divide α by the rank r, so the scale is α / r.
Predict first
Set the scale α / r to 0. What does the adapted model answer?
A scale of 0 multiplies the correction by zero, so the used weights are exactly W: the base model.
Live toy · one weight matrix and the next token
Step 1. The two small trained tables. B is tall and thin, A is short and wide; their width is the rank r.
B 4,096 rows × r
×
A r × 4,096 columns
=
B × A full size, 4,096 × 4,096
Step 2. Scale the correction by α / r and add it to the frozen table.
W frozen
(α / r) × (B × A) scaled correction
W + (α / r) × (B × A) used
Every table is shown as a 6 × 6 corner of the real 4,096 × 4,096 size (“×” reads “by”: rows by columns). The thin tables are drawn with up to 4 columns; the slider sets the real r. Green is positive, blue is negative.
1.00
8
Reply to customer: “Your order ___”
Full fine-tuning, per matrix
0
LoRA, per matrix
0
Share trained, this matrix
0
Live toy · forgetting: two eval curves, your task and everything else
3
Client task eval
–
General skills eval
–
Illustrative curves in the pattern of LoRA Learns Less and Forgets Less (Biderman et al., 2024): full fine-tuning gains a bit more on the target domain and loses more on everything else. Keep a general eval set next to your task set, and stop where the task curve flattens.
Live toy · how much of a whole 8B model does LoRA train?
Trained parameters
0
Share of 8.03 B
0
Adapter file, BF16
0
Llama-3-style 8B: for each targeted matrix, LoRA adds r × (inputs + outputs) weights per layer. Thinking Machines’ LoRA Without Regret (2025) found that attention-only LoRA underperforms even at higher rank, while LoRA on all layers with about 10× the full fine-tuning learning rate matches full fine-tuning on post-training-sized datasets.
Fine-tuning hygiene · settings that quietly ruin a run
One training batch: four examples (colours), sequence length 32, grey stripes are padding
Tokens that count in the loss
0
Padding wasted
0
LoRA learning rate
≈ 10× full FT
Typical starting points: full fine-tuning about 1e-5 to 2e-5, LoRA about 1e-4 to 2e-4. Packing must keep attention inside each example, or the examples leak into each other.
TrySet the scale to 0. Left and right matrices match and the model answers like the base model, formal “has been shipped”. At 1 the adapter, trained on the client’s casual replies, pushes “is on its way”. In a real config, r=16, lora_alpha=32 means a scale of 2; doubling r without changing alpha halves it. In the forgetting toy, compare full fine-tuning with LoRA over more epochs: the task curve rises in both, the general-skills curve falls faster with full fine-tuning.
Common mistakeUsing attention-only LoRA with a tiny rank and concluding that LoRA is weak. Target all linear layers, including the MLP, and raise the learning rate.
Essential takeawayLoRA freezes the base weights and learns a low-rank update B·A. On an 8B model it trains about 0.05–2% of the parameters, depending on the rank and which layers it targets. Applied to all layers, including the MLP, with a learning rate about 10× that of full fine-tuning, it matches full fine-tuning on typical post-training datasets; it falls behind on pre-training-sized data. Get the hygiene right: the model’s own chat template, loss on the answer only, packing without cross-talk.
Making 4 · Preferences
Preferences: RLHF and DPO on the same answer pairs
Same input, people’s choices between two answers. Two different machines to turn them into a better model.
Plain modeThe AI writes two answers and you pick the nicer one, like voting for the better drawing. RLHF first trains a judge who learns what you like, and the judge then coaches the AI. DPO skips the judge and learns straight from your votes.
Key ideaPeople pick the better answer of a pair. RLHF trains a reward model on that, then runs PPO, which also needs a value model. DPO trains the model directly on the pairs. When a program can check the answer, the next bench’s GRPO replaces both.
Predict first
You click “A is better” once. Whose answers change first?
DPO learns straight from the pair. RLHF first has to train its reward model before PPO can move the policy.
Live toy · you are the human labeller
Customer: “Where is my order #4471?”
Answer A
Your order shipped on Monday and should arrive on Thursday. Here is your tracking link.
Answer B
Your order is being processed.
RLHF
Pair→Reward model→PPO→Policy
Reward scores: A 0.00, B 0.00
In memory: policy, reference, reward model and value model: four models at once.
DPO
Pair→Policy
No reward model: the gradient comes straight from the pair.
In memory: policy and reference. Simpler and more stable.
TryClick “A is better” five times. RLHF first has to train the reward model, only then does the policy move; DPO moves at once. Then click “B is better” twice, which is label noise, and see who reacts more.
Common mistakeReading a falling DPO loss as better answers. The loss can drop while answers get longer or drift from what users want; check on your eval set and watch answer length.
Essential takeawayRLHF trains a reward model on preference pairs and optimises the policy with PPO under a KL penalty to the reference. DPO reaches a similar goal directly from the pairs, with no reward model and no RL loop, so it is cheaper and more stable. Use them for taste; use RL with a verifier for correctness.
Making 5 · RL and reasoning
RL with verifiable rewards: let a checker grade the answers
Reasoning models are trained by letting them try problems many times and rewarding the attempts a program can verify. No human labels, no reward model and no critic network.
Plain modeThe AI does the same homework question 8 times. A calculator marks each try right or wrong. Tries that did better than the AI’s own average are encouraged, worse ones discouraged. If all 8 are right, or all wrong, there is nothing to learn from that question.
Key ideaGRPO samples a group of answers per prompt. A verifier scores each one: 1 if correct, 0 if not. Each answer’s advantage is (its reward − group mean) ÷ group standard deviation, so the group itself is the baseline and no value model is needed.
Predict first
All 8 sampled answers to a problem are correct. How much does the model learn from this problem?
Every reward equals the group mean, so every advantage is 0 and the gradient is 0. The same happens when all 8 are wrong. Only problems with mixed results teach anything, which is why problem difficulty matters so much.
Live toy · “A customer orders 3 items at €12.40 each plus €5.00 shipping. What is the total?”
Group mean reward
–
Learning signal
–
True accuracy
–
Rounds
0
The model’s probability for each way of answering
Live toy · test-time compute: sample more answers when answering
pass@k counts a success if any of the k answers is right, so it needs a checker to find that answer. Majority vote returns the most common final answer and needs no checker; here the wrong answers are spread over three different totals. Reasoning models get a similar gain inside one answer by thinking longer.
Live toy · agent RL: several tool calls, one reward at the end
Task: “Refund order 5531 if it arrived damaged.” The agent should look up the order, check the refund policy, then issue the refund. Eight episodes per round, scored only at the end.
Illustrative policy. Real agent RL runs thousands of episodes in a sandbox with simulated tools and APIs (an environment), and uses group-relative advantages as in GRPO: each episode’s reward minus the group’s mean. Switch the policy check out of the reward to see reward hacking appear.
The verifier ladder · a checker is useful long before RL
1. Check at answer timeRun the checker on every answer; retry when it fails, or sample n answers and keep one that passes (best of n). No training at all, works with any API.
2. Train on approved answersKeep the answers the checker approved and fine-tune on them (rejection sampling, then SFT). The model learns to pass more often in one try.
3. RL with the checkerOnly now: GRPO uses the checker as the reward. Needs open weights or a provider’s reinforcement fine-tuning, and problems the model solves some of the time.
Climb only as far as you need. Step 1 often fixes the product; steps 2 and 3 cut the cost of retries.
TrySample and update a few times at the right difficulty: accuracy climbs. Switch to “Too easy” or “Too hard”: most groups are all right or all wrong, the learning signal drops to zero and nothing moves. Then switch the checker to “Only checks the format” and run 30 rounds: reward reaches 100% while true accuracy stalls. That is reward hacking.
Common mistakeTraining on problems the model always or never solves. Their advantages are all zero, so they cost compute and teach nothing. Filter for problems with mixed results (the DAPO paper calls this dynamic sampling).
Essential takeawayRL with verifiable rewards needs prompts and a checker, not labelled answers. GRPO samples a group per prompt and uses the group mean as the baseline, so unlike PPO it needs no value model. It learns only from prompts with mixed results, and it optimises exactly what the checker measures, so a weak checker gets gamed.
What the student can learn depends on what the teacher reveals: a full distribution, one answer, or just text.
Plain modeA good teacher does not just say “the answer is mat”. She says “mat is best, rug is almost as good, tractor is silly”. A student who hears all of that learns much faster than one who only hears the answer.
Key ideaBehaviour is transferred, not weights. It works best on soft labels, the teacher’s full distribution. A closed API returns only text, so that is training on synthetic data.
Predict first
Raise the teacher’s temperature from 1 to 3. What does the student get to see?
Higher temperature flattens the distribution, so the near misses become visible to the student. The order of the words stays the same.
Live toy · the teacher sees “The cat sat on the ___”
1.0
Student receives
0
Information (entropy)
0
Live toy · on-policy distillation: the student writes, the teacher grades every token
Reply to customer: “Your order ___”
Feedback signals
0
Trained on
–
On-policy distillation minimises the per-token reverse KL between student and teacher on text the student wrote. Thinking Machines (2025) report matching RL-trained reasoning results at a fraction of the compute; Qwen3 used distillation from its large models to train its small ones.
TryRaise T to 3. The student now sees that “rug” is almost as good as “mat” and “tractor” is off. Then switch to “Closed API” and see what is lost.
Common mistakePlanning logit distillation from a closed API. You get text and at most a few log-probabilities, so it is sequence-level distillation, and the terms of service usually forbid training a competing model.
Essential takeawayLogit distillation trains the student on the teacher’s full softened distribution. With a closed API you only get text, so it is sequence-level distillation on synthetic data, and the licence usually forbids it. On-policy distillation lets the student write and the teacher grade every token: dense feedback on the student’s own mistakes.
Making 7 · Compression
Quantization coarsens numbers, it does not shorten vectors
Fewer bits per number, same number of numbers. Memory falls, quality drops a little, then a lot.
Plain modeThink of a picture painted with a thousand colours, then painted again with only 16 crayons. Same picture, same number of dots, just fewer colours. It takes less space and looks almost the same, until you use only 2 crayons.
Key ideaThe vector keeps all 4096 numbers (its dimension). Each number is stored with fewer bits and snaps to the nearest step of a grid.
Predict first
INT4 versus FP16: how much smaller is a 7B model’s weight file?
Each weight takes 4 bits, plus a 16-bit scale shared by every group of 128 weights: about 4.1–4.25 bits in total, so 3.8–3.9× smaller.
Live toy · 8 of the 4096 numbers in the embedding of “cat”
−10+1originalstoredinteger × step
Vector dimension
4096
Vector size
0
7B model file
0
Smaller than FP16
0
Mean error
0
original valuewhat is storedallowed steps (shown up to 4 bits)rounding error
Running example, after LoRA: “Your order ___” at this precision
Integer formats store one 16-bit scale per group of 128 weights: about 0.125 extra bits per weight, so INT4 is about 3.9× smaller than FP16, not 4× (3.8× with a zero point too). The KV cache and activations stay 16-bit unless you quantize them separately.
TrySwitch from FP16 to INT4. Dimension stays 4096, memory drops about 3.9×, error grows a little and the running example still says “is on its way”. At 2 bits values merge, the probabilities shift and quality breaks.
Common mistakeShipping a quantized model without re-running the eval set. Average quality may barely move while specific skills, such as maths or rare languages, drop.
Essential takeawayQuantization lowers the bits per weight, not the dimension. With group-wise scales, INT4 cuts weight memory about 3.7–3.9× versus FP16; the KV cache and activations shrink only if you quantize them too. Always re-run the eval set to measure the quality cost before shipping.
Part four
Choose, measure, serve
Choose 1 · In context or in weights
In context or in weights: where should the knowledge live?
A model can use what you put in the prompt (in context) or what training put into its parameters (in weights). This one distinction explains prompting versus RAG versus fine-tuning, and most of the frontier.
Plain modeA cheat sheet on the desk, or what you learned by heart. The cheat sheet is exact and easy to replace, but you have to bring it every time. What you learned by heart is always with you, but it is fuzzy and slow to update.
Key ideaIn-context learning: the model adapts to the examples and documents in the prompt, for that one request. Exact, changeable at once, paid in tokens on every call (much less with caching), and limited by the context window. In-weights learning: training changes the parameters. Free per call and always there, but it needs data and a training run, updates slowly, can forget other skills and stores facts only approximately. Facts that change go in context; stable behaviour, format and style go in weights.
Predict first
A customer’s 3,000-token price list changes every week, and the assistant must quote it exactly. Where does it belong?
Exact and changing weekly: context. With caching, 3,000 tokens per call cost little, and a change is live with the next request. A weekly fine-tune would cost a training run each time and still quote prices only approximately.
Live toy · four kinds of knowledge, three places to put them
Costs at Sonnet 5.5 prices: $2 per million input tokens, $0.10 for cache reads, retrieval adds about 3,000 uncached tokens per call. A LoRA run is counted at $50 of GPU time; the people time is extra.
Where the line is blurring
Long context: million-token windows plus caching make “put the whole manual in the prompt” a real option when the corpus is small and stable.
Fast and slow weights:Fast-Slow Training (2026) keeps an optimised prompt as fast weights next to the model’s slow weights, and reports less forgetting than RL on the weights alone.
Document to adapter:Doc-to-LoRA turns a document into a LoRA adapter in one forward pass: context converted into weights.
Test-time training: layers that keep learning while the model reads (see Beyond next-token).
TryPick the price list: in context with caching wins on cost and exactness. Pick the tone of voice: it is behaviour, used on every call, so it belongs in the weights once you have examples. Pick the 2-million-token manual: it does not fit a context window, so RAG retrieves the few pages each question needs. Raise the requests to a million a day and watch what a long prompt costs, even cached.
Common mistakeFine-tuning to teach facts. The model learns to sound as if it knows them, quotes them approximately, and has to be retrained at every change. Teach behaviour with training, supply facts in context.
Essential takeawayIn context means exact, instant to change and paid per call; in weights means approximate, slow to change and free per call. Put changing facts in context (prompt, cache or RAG) and stable behaviour in weights. Most frontier work, from long context to fast weights, moves things across this line.
Where to choose what: prompt, RAG, LoRA, RL, distil or quantize?
The most expensive mistake in an LLM project is pulling the wrong lever. Describe the problem and get a recommendation, the reason for it, and what would change it.
Plain modeIf the assistant does not know your prices, give it the price list (RAG). If it knows them but answers rudely, coach it (fine-tuning). If it gets sums wrong, give it homework with an answer key (RL). If it is too slow, let it train a smaller, quicker assistant (distillation).
Key ideaChanging facts → RAG. Behaviour and format → LoRA SFT. Correctness a program can check → RL with a verifier. Cost and latency → distillation plus quantization. A strong prompt is always the baseline every option has to beat. Then check what you can touch: with API access only, prompt, RAG, typed output and the provider’s fine-tuning are all there is; with open weights you also get LoRA, RL, quantization, steering and merging.
Predict first
A client’s product catalogue changes every week and the assistant quotes old prices. What is the right first fix?
Facts that change go to retrieval. A fine-tune would learn last week’s prices and need retraining every week, and fine-tuning stores facts poorly anyway.
Live toy · start here: read 50 failures and tag them before choosing a fix
Illustrative tags for three typical projects. Error analysis is the cheapest step in the whole lab: one afternoon, a spreadsheet and 50 real failures from your eval set. Fix the biggest bucket first.
Levers people forget, before any training
Few-shot and automatic prompt optimisation: tools such as DSPy or GEPA rewrite instructions and choose examples against your eval set.
A bigger model or a cascade: send easy requests to a small model and escalate the rest; often cheaper than fine-tuning the small one.
Tool calls: a calculator, code, SQL or an API for arithmetic, live data and actions, instead of hoping the model knows.
Long context with caching instead of RAG: if the corpus is small and stable, send all of it, cached (see In context or in weights).
Tune the retriever, not the generator: when the wrong document comes back, fix chunking, add hybrid search or a reranker, or fine-tune the embedding model (see Retrieval toolkit).
Decision bench · describe the situation
start hererecommendedlater, if neededavoid for this problem
Why
What would change this answer
Who picks the route · the customer’s constraints come first
The bench above says which lever fits the problem. In a customer project the same problem can still end up on different routes, because the customer’s situation decides. Ask these questions before you propose anything.
Can the data leave their environment?No → an open model they host, or a frontier model inside their own cloud account (Bedrock, Vertex, Azure) if their rules allow it.
Which cloud and contracts do they already have?An existing AWS, Google or Azure commitment usually decides which frontier models are on the table at all.
How much traffic, how fast?Low or uneven volume → pay per token through an API. High, steady volume on a narrow task → a small fine-tuned model can be much cheaper.
Who will run it?Hosting needs people who run GPUs, updates and monitoring. Without that team, an API or a managed endpoint is safer.
Does it have to work offline or on a device?Then only a small open model, quantized, is possible.
Which licences and terms apply?Open-weight licences differ, and API terms limit training on outputs. Legal checks this before data is generated.
Often the answer is a mix: a frontier API now to prove value, then a fine-tuned or hosted model once volume and requirements are clear, with the same eval set deciding both steps.
TryPick “Model gets order totals wrong”, then switch the checker to “No”: RL drops out and distillation from a stronger model takes its place. Switch access to “API only”: quantize, merge and your own RL drop out. Try “Customer asks to delete their data”: there is no lever that removes it reliably, only retraining without it. Then pick “Catalogue changes weekly” and raise the data to 100,000+: fine-tuning still does not become the answer for facts.
Common mistakeFine-tuning to add facts. The model picks up the style of the answers more reliably than the facts, cannot say where they came from, and is out of date the next time the data changes.
Essential takeawayDiagnose before you train. Missing or changing knowledge is a retrieval problem, wrong behaviour is a fine-tuning problem, and cost is a distillation and quantization problem. When a program can check the answer, use the checker in steps: at answer time first (retry, best of n), then fine-tune on checker-approved answers, then RL. Your access level limits the levers, and nothing makes a model reliably forget. Keep the prompted model as the baseline on your eval set.
A frontier API in the loop: data writer, judge, research engineer and production partner
Which model a project uses is the customer’s call: a frontier API (Claude, GPT, Gemini, directly or through AWS Bedrock, Google Vertex or Azure), an open model they fine-tune, a model they host themselves, or no training at all. Even teams that train or host their own model often use a frontier model around it: to write and check data, to judge evals, to run experiments, and for hard cases in production. This bench uses Claude as the worked example; the roles, cost levers and terms questions are the same for any provider.
Plain modeA frontier model is like a senior colleague who helps write the exercises, marks the tests and runs the lab equipment. Your own small model is the specialist you train for one job. One rule: you may not use the colleague’s work to build a rival to the colleague’s company.
Key ideaUse a frontier model where judgement is scarce and volume is moderate: seed data, review, judging, hard cases. Use your own fine-tuned model where volume is high and the task is narrow, or where the customer’s data may not leave their cloud. Prompt caching and the Batch API cut the cost of big offline jobs, and on Claude the two discounts stack.
Predict first
An overnight eval job: 100,000 judging requests on Sonnet 5.5, each with the same 20,000-token rubric. Which option costs least?
They stack. With the defaults in the calculator, the plain job costs about $4,600, the Batch API alone about $2,300, caching alone about $1,040, and both together about $520: the batch halves every token, and caching turns the repeated rubric into cheap cache reads.
Live map · five jobs for a frontier model around your own model, click one
Live toy · what does an offline API job cost? (Claude prices as the example)
Prices in US dollars per million tokens from Anthropic’s pricing page, November 2026: input, output, cache write (1.25× input for 5 minutes) and cache read. The Batch API halves input and output, and cache multipliers stack with it. Haiku 5.5 charges higher rates for prompts over 100,000 tokens. Cache hits inside a batch are not guaranteed, hence the hit-rate slider. Opus, Sonnet and Haiku 5.5 use the newer tokenizer that arrived with Claude 4.7: the same text is about 30% more tokens than on Claude 4.6-era models, so compare costs per request, not per token. OpenAI and Google also offer batch and cached-input discounts, at their own rates and rules. Check the live pricing pages before you budget.
Training on a provider’s outputs: what the terms say (Claude as the example)
Anthropic’s Commercial Terms (version of 17 June 2025) say the customer “owns its Outputs” (Section B), and also that customers may not “access the Services to build a competing product or service, including to train competing AI models” (Section D.4).
Using Claude as a judge, a reviewer or a research engineer for your own model is not training on its outputs. Fine-tuning on data Claude wrote is, and that is where the competing-model clause matters.
Questions to clear with your legal team: is the model you train a competing AI model or service? Which terms apply to you (direct API, AWS Bedrock and Google Vertex have their own versions)? Does the training data also contain customer or personal data?
Other providers’ terms have their own rules on using outputs to build models; read the ones the customer has signed. This is a summary of public terms, not legal advice; your contract decides.
TryPick “Overnight eval with a judge” and compare the four bars: caching and batch together cut the bill by close to nine tenths. Switch the model to Haiku 5.5: the same job costs a few tens of dollars, so check whether the cheaper judge still agrees with your human labels. Then pick “Synthetic data”: most of the cost is now output tokens, which caching cannot touch.
Common mistakeFine-tuning a small model on API-written data and never checking it. Generated data repeats the generator’s style and mistakes; hand-check a sample, deduplicate, keep a held-out set the generator never wrote, and judge the result with labels from people, not only with the same model that wrote the data.
Essential takeawayWhich route a project takes is the customer’s decision. Whatever they choose, a frontier model like Claude fits around your own training as data writer, judge, verifier author, research engineer and production partner for hard cases. Cut offline costs with prompt caching and the Batch API, which stack. Fine-tuning on Claude-written data is the step the terms restrict when the result competes with Anthropic, so clear that question first.
Typed output: make the model return data your code can trust
An app does not want a nice sentence; it wants an object with the right fields and types. Three layers get you there: describe the type, enforce it while the model writes, and validate it anyway.
Plain modeA form with boxes is easier to check than a letter. Constrained decoding is a form where the pen simply will not write a letter into the number box. But the form cannot tell whether the number you wrote is true.
Key ideaWrite the type once as a JSON Schema, usually generated from Pydantic or Zod. Constrained decoding then sets the probability of every token that would break the schema to zero before each pick, so the output always parses and matches the type. It guarantees the shape, not the truth: the values still need checking.
Predict first
With constrained decoding on, can the model still return the wrong order status?
The schema only limits status to processing, shipped, delivered or cancelled. If the order was delivered and the model says “shipped”, the output is perfectly valid and wrong. Checking values against your own systems is a separate step.
Live toy · the customer-reply model has to return an order update as typed JSON
class OrderReply(BaseModel): order_id: str = Field(pattern=r"^\d+$") status: Literal["processing", "shipped", "delivered", "cancelled"] eta_days: int = Field(ge=0, le=30) model_config = ConfigDict(extra="forbid") # no other fields
Model calls
1
Parses as JSON
–
Matches the type
–
Matches the order system
–
Token candidates and probabilities are illustrative; the validation is real: the finished text is parsed and checked against the type above. Constrained decoding is built into local servers (vLLM with XGrammar, llama.cpp grammars, the Outlines library); most model APIs accept a JSON Schema for the response or for tool calls. JSON mode alone guarantees valid JSON, not your schema.
Models that only judge and never write, such as Jev, are not constrained generation: they have no tokens to mask. They have their own bench: Encoders and embeddings.
TryPick “Free text” and write the rest: the model adds a friendly sentence, invents “on its way” and writes “Thursday” into a number field, so nothing parses. “Validate and retry” fixes it, at the cost of a second call. “Constrained decoding” gets it right in one pass: watch the masked tokens. Then switch the truth to “delivered yesterday”: the typed answer still says “shipped”, and only the fact check notices.
Common mistakeTreating schema-valid output as correct output. Types, enums and ranges catch malformed answers; whether the status is true still has to be checked against your own systems. And keep a free-text reasoning field before the answer fields if the task needs thinking: forcing the answer first can hurt accuracy.
Essential takeawayType-safe output has three layers: describe the type once (Pydantic or Zod, exported as JSON Schema), enforce it while generating (constrained decoding masks every token that would break it, or the provider’s strict schema mode), and validate it in code anyway. That gives output that always parses and has the right types, not output that is true.
Encoders and embeddings: models that read, compare and decide
Not every model writes. An encoder reads the whole text at once and returns a vector or a score. It powers search, RAG retrieval, reranking, classification, and decision models such as Jev.
Plain modeA librarian who never writes books, but can tell you in a second which shelf a book belongs on, which two books are about the same thing, and how sure she is.
Key ideaAn encoder (BERT, ModernBERT) turns a text into one embedding. Trained with a contrastive loss, matching pairs end up close and the rest far apart. A bi-encoder embeds query and documents separately, so document vectors are computed once; a reranker reads query and document together, slower but more accurate. A classification head on top turns the vector into a probability per label in one forward pass.
Predict first
One million documents, and the best 5 for a query in under 100 ms. What runs first?
A reranker needs one forward pass per document: a million passes per query. Bi-encoder document vectors are computed once in advance; the query needs one pass and a nearest-neighbour search. The reranker then fixes the order of the top 50.
Live toy · contrastive training: pull matching pairs together, push the rest apart
0
Matching pairs, similarity
–
Other pairs, similarity
–
Right answer ranked first
–
Illustrative positions in 2 of the 768 or more dimensions. In each training batch, every question must give its own answer a higher similarity than all the other answers in the batch (InfoNCE loss), so the other pairs act as free negatives.
Live toy · bi-encoder, reranker, or both
Illustrative figures: about 15 ms for the query embedding and the vector search, about 0.5 ms per query–document pair on a GPU for the reranker, and typical recall@5 levels from retrieval benchmarks. Measure both on your own documents.
Live toy · a decision model: statements in, confidences out (the Jev pattern)
Instead of writing a reply, the model only judges statements about a state your code sends, all in one request, and returns a confidence for each in a fixed format. Your code decides what happens.
{"customer_message": "The parcel arrived broken. I want my money back or a new one.", "order": {"id": "4471", "status": "delivered", "days_since_delivery": 2}}
85%
TypeSafe AI’s Jev works this way: early access since 15 September 2026 (version 1.13), a cloud-only “System One” model trained for calibrated confidences, with no memory between requests. It has three question types: Noul (one yes/no probability), Choice (one option from up to 255, with a probability for each) and Score (a position on an ordered scale of 2–10 levels). State plus all questions must fit in 64k tokens, and state plus the longest single question in 32k. Independent tests now exist. Vals AI (6 October 2026) found it tied with several frontier models on 400 claim-verification items (97.5%) at about 1/500th of the most expensive model’s price, but last of twelve systems on a LegalBench slice; at a 1% error budget it automated 95% of cases with 1.6% error. A pre-registered test found accuracy fell to 16.7% when the criteria in the question were wrong, while it still answered out-of-scope messages at 0.99 confidence: calibrated on the task it was built for, overconfident outside it. Its guide names weak spots: counting, dates (read as text), literal reading of the question, and material in the state that the question does not need. No EU region is documented, so check data residency before EU client data goes in. Open models with the same interface run in your own network: Laya (ModernBERT-large, 421 M parameters, Apache 2.0) and openJev (ModernBERT-base). How it works inside: open rebuilds such as PayPal.AI’s list the options with letters and read a softmax over the letters’ logits in one forward pass, no text generated. That is the output layer from Weights in action, with the options as the rows.
Live toy · three question types and a calibration plot
Calibration plot from 1,000 illustrative decisions, grouped by stated confidence. On the diagonal, “90% sure” is right 90% of the time. Temperature scaling on a held-out set moves a curve back towards the diagonal without changing which answer wins.
Capstone · train your own decision model
1. LabelsExport 1,000–5,000 real requests with the right label, or let an LLM label them and check a sample by hand.
2. TrainFine-tune ModernBERT with a classification head on them: minutes on one GPU, a model of a few hundred MB.
3. CalibrateFit temperature scaling on a held-out set and check the calibration plot.
4. Decide in codeSet thresholds per label; send low-confidence requests to an LLM or a person, and log them as the next training data.
Same interface as Jev: per-option probabilities from one forward pass. You own the weights, so it runs in the customer’s network.
TryMove the training steps from 0 to 10: questions find their answers, and the right answer moves to rank 1 for all four. Then switch the pipeline to “Reranker over everything” at 1 million documents: more accurate, but minutes per query. In the decision toy, switch to the overconfident model: the same code now refunds automatically, although the customer also asked for a replacement; the calibration plot shows why.
Common mistakeTreating cosine similarity from a generic embedding model as a probability. A similarity of 0.82 is not “82% sure”, and generic embeddings often place opposite statements about the same topic close together. For decisions, train a head on labelled data and calibrate it.
Essential takeawayEncoders read, they do not write. Contrastive training makes embeddings for search and RAG; bi-encoders find candidates fast and rerankers order them well; a classification head turns an encoder into a decision model with a probability per label. That covers routing, classification and checks for a fraction of an LLM’s cost, and only calibrated scores make thresholds in code meaningful.
The back-of-envelope maths every LLM project needs: weights, gradients, optimizer state, activations and KV cache, now with a mixture-of-experts model.
Plain modeA GPU is like a backpack. The AI’s brain, its notes while it learns, and its memory of the conversation all have to fit inside. Pack too much, and the zip will not close.
Why it mattersModel size, context length, latency and cost are traded against each other in every project. LoRA, QLoRA, FSDP and vLLM are the usual levers.
Predict first
Does a full fine-tune of an 8B model with AdamW fit on one 80 GB H100?
About 16 bytes per parameter: 2 for BF16 weights, 2 for gradients and 12 for AdamW state. 16 × 8 B = 128 GB.
Live toy · memory per GPU
4k
1
1
Read from GPU memory for every decoding step (one new token per request)
Per GPU
0
Verdict
–
KV cache = weights at
–
Compute busy while decoding
–
TryWatch the second bar: at 8B, 4k context and 1 request the weights are almost all of the memory traffic and the GPU computes under 1% of the time. Raise the requests to 32: the KV share passes half at about 120k tokens in total (32 × 4k), whatever the split. Switch to INT4 weights and the crossover moves down to about 30k. 70B inference in FP16 on one H100: no. INT4: yes. Now 128k context with 8 requests: the KV cache eats the GPU. Push one request to 1M tokens and even an 8B model needs well over one H100 for its KV cache alone. Then an 8B full fine-tune on one GPU (no), on 8 GPUs with FSDP, and with QLoRA on one.
Common mistakeForgetting the KV cache, or sizing a MoE model by its active parameters. Weights fit, then 32 users at 32k context add tens of GB; and a 30B-A3B model needs memory for all 30 B.
Essential takeaway“Inference memory is weights plus KV cache. A full fine-tune with AdamW needs about 16 bytes per parameter before activations, so an 8B model needs sharding with FSDP or ZeRO-3, or QLoRA on a single GPU.”
Serving: the KV cache, batching and tricks that cut latency
Once the model fits, serving is a game of memory bandwidth. These toys serve the customer-reply model: an 8B Llama-style model in BF16 on one 80 GB H100.
Plain modeA waiter carries one heavy tray (the model’s weights) to the tables for every single word. Carrying the orders of 32 tables on the same trip is barely slower than one, so serving many people at once is far cheaper per person.
Key ideaEvery new token reads all the weights from GPU memory, so decoding is memory-bound. Batching shares that read: throughput rises a lot while each user slows a little. The KV cache grows linearly with tokens × users: 2 × layers × KV heads × head dimension × bytes, per token.
Predict first
Going from 1 to 32 users on the same GPU, what happens to each user’s speed in tokens per second?
Each step reads the 16 GB of weights once for the whole batch. Extra users add only their KV-cache reads and a little compute, so in this toy each user slows to well under half while total output grows more than ten times.
Live toy · KV cache size
weights 16 GBKV cacheH100, 80 GB
KV cache per token
–
KV cache, all users
–
Verdict
–
Live toy · latency against throughput
Each user
–
All users
–
Time to first token
–
Speculative speed-up
–
Illustrative model: each decoding step reads the 16 GB of weights at 3.35 TB/s, plus every user’s KV cache, plus a small compute cost per user. Prefill runs at about 25,000 tokens per second; each request has a 2,000-token system prompt, 200 tokens from the user and a 300-token answer. Speculative decoding assumes a draft model 5% of the cost of the main one, and its gain shrinks as the batch fills the GPU. Measure your own engine with a load test.
Live toy · break-even: when does a rented GPU beat paying per token?
GPUs needed
–
Break-even
–
The GPU is billed for every hour, busy or not; the API only for tokens used. The calculator counts GPU hours only: add the people who run, patch and monitor it, which often decides the question at low volume. The blended API price mixes input and output at your ratio.
TryMove users from 1 to 32: each user slows down, the total climbs steeply. Push the context to 128k with 32 users: the KV cache no longer fits. Switch GQA to MHA (4× bigger) and to MLA (much smaller). Turn on prefix caching: the time to first token drops from about 90 ms to under 10 ms. At 1 user, add 4 draft tokens.
Common mistakeBenchmarking with one request at a time. Latency and cost per token at 1 user say little about 32 users; measure time to first token and tokens per second at 1, 8 and 32 concurrent users.
Essential takeawayServing is bound by memory bandwidth and the KV cache. Continuous batching keeps the GPU full, prefix caching skips repeated prompt starts, GQA or MLA shrink the KV cache, and speculative decoding lets a small draft model propose tokens that the big model checks in one pass.
The rest of the toolbox: before you reach for an LLM
Toolbox 1 · Not every problem needs an LLM
Rules, classic ML and older NLP: when they beat an LLM
Many production problems are tables, numbers or fixed patterns. There a rule, a regular expression or a gradient-boosted tree is often more accurate, far cheaper and easy to explain. They also set the baseline any LLM has to beat.
Plain modeYou would not ask a poet to check whether an IBAN has the right number of digits. A ruler does that perfectly, every time, for free. Keep the poet for the letters.
Key ideaIf the rule can be written down (formats, dates, totals, thresholds), write code. For tables of numbers and categories with a known outcome, use gradient-boosted trees (XGBoost, LightGBM): they still beat deep learning on most tabular benchmarks. For text with fixed labels and many examples, TF-IDF with logistic regression is a strong cheap baseline, and a fine-tuned encoder beats it. Use an LLM when the input is open-ended language or the task keeps changing.
Predict first
A dealer network wants to know which customers will skip their next service, from 40 columns of visit history. What do you try first?
A table with a labelled outcome is the home ground of gradient-boosted trees: quick to train, strong, and they show which columns matter. An LLM reading rows as text is slower, costlier and usually weaker on numbers. The one-line rule is the baseline to beat, not the answer.
Live toy · routing support tickets into 12 queues: four tools on the same job
Illustrative accuracies in the usual pattern; your eval set decides. Costs: the LLM row uses Sonnet 5.5 prices for about 300 input and 10 output tokens per ticket; encoder and TF-IDF run on a small server you already pay for, counted at a share of its hourly price.
Live quiz · which tool for which job? Pick one per card
Older tools, still at work
BM25 and TF-IDF (1970s–1990s): still the default ranking in Elasticsearch and OpenSearch, and half of every good hybrid search (see Retrieval toolkit).
word2vec and fastText (2013, 2016): one vector per word, trained in minutes on a CPU. fastText still detects the language of a text in microseconds, and its classifiers are a common baseline.
Regular expressions and CRFs: extract part numbers, IBANs, order IDs and dates exactly; CRF taggers still run named-entity extraction where every millisecond counts.
n-gram language models: still inside keyboard suggestions, spell checkers and some speech decoders, because they are tiny and fast.
Gradient-boosted trees: the standard for credit scoring, churn, demand and fraud tables. For small tables, the tabular foundation model TabPFN (Nature, 2025) beats tuned tree ensembles on datasets up to 10,000 rows in seconds.
TrySet the examples to “none”: only the rules and the LLM can work at all, and the LLM wins. Slide to 10,000 examples: the encoder is more accurate than the prompted LLM, answers in milliseconds and costs a fraction. Then take the quiz: most jobs that sound like “AI” are rules or tables.
Common mistakeUsing an LLM where a validation rule exists. The LLM is right 99% of the time and the rule 100%, and the 1% lands in production, without an error message. The second mistake is skipping the baseline: if TF-IDF scores 88%, an LLM at 89% is not worth its bill.
Essential takeawayWrite code for anything you can state as a rule, use gradient-boosted trees for tables, and start text classification with a cheap baseline before an encoder or an LLM. Older tools such as BM25, fastText and regular expressions are still the fastest correct answer for their jobs. LLMs earn their cost on open-ended language and changing tasks.
Time series and anomalies: learn what normal looks like first
Sensor readings, sales and machine logs are numbers in time. The strongest first step is a seasonal baseline and a check on what is left over. An LLM is a weak tool for reading thousands of numbers, and a good one for explaining the alert afterwards.
Plain modeTo notice that a fridge is too warm, first learn how warm it usually is at each hour of the day. Anything far from its usual value for that hour is worth a look, even if it is not the warmest reading of the week.
Key ideaSplit a series into trend, season and residual. Forecast first with a seasonal naive baseline (the same hour last week), then with gradient-boosted trees on lag features or a time-series foundation model that forecasts without training (Chronos-2, TimesFM). Detect anomalies on the residual, not the raw value: a fixed threshold misses a night-time fault and fires on every normal peak.
Predict first
A machine’s power draw peaks every working day at 10:00, and a fixed alarm at 80 kW fires every morning. What fixes it?
The peak is normal; the alarm compares against the wrong thing. Comparing with the usual value for that hour and weekday stops the false alarms and also catches faults far below the peak, such as a load at 3 a.m. Raising the threshold only hides more faults.
Live toy · two weeks of hourly power draw, with three faults hidden in the second week
readingexpected for that houralertreal fault
Faults caught
–
False alarms (hours)
–
Synthetic data drawn by the page. The first week is clean and teaches the “expected” curve: the median for each hour of the week. Faults: a load at 3 a.m. on day 10, half load on days 11 and 12, and a slow drift from day 13 (a bearing wearing out).
Forecasting and the role of LLMs
Baseline first: “same hour last week” is hard to beat for many operational series. Report every model against it.
Trees on lag features: last week’s value, last day’s value, calendar features and holidays into LightGBM: the workhorse of demand forecasting.
Foundation models:Chronos-2 (Amazon, 2025) and TimesFM (Google) forecast unseen series zero-shot, which helps with thousands of short series and no data science team.
LLMs: explain an alert in words, write the query that fetches the data, summarise the incident. Not the detector.
TryWith the fixed threshold, raise the sensitivity: either every morning peak fires or the 3 a.m. fault is missed. The rolling z-score catches the spike but treats the half-load days as the new normal after a day. The seasonal residual catches all three at medium sensitivity with almost no false alarms.
Common mistakeJudging a forecast or a detector without a baseline and without labelled past incidents. Collect the dates of real faults first; precision and recall on them decide, not a nice-looking chart.
Essential takeawayModel what normal looks like (trend and season), then forecast with a seasonal baseline, trees or a time-series foundation model, and detect anomalies on the residual. Use LLMs around the numbers, to fetch, explain and report, not to read them.
Computer vision without an LLM: YOLO, ORB and the frameworks behind them
Finding scratches on a part, counting boxes on a pallet or checking that a label is present: a small detector such as YOLO, or a classic feature matcher, does this in milliseconds on a camera box. A vision-language model is slower, costlier and still the better tool for open questions about an image.
Plain modeA sniffer dog finds one thing very fast and never gets tired. A professor can describe anything you show her, but slowly. On an assembly line you want the dog; for an odd case you call the professor.
Key ideaAn object detector (YOLO) predicts boxes, classes and confidences for the whole image in one forward pass. Post-processing keeps boxes above a confidence threshold and removes duplicates with non-maximum suppression: of two boxes that overlap by more than an IoU limit, the weaker one goes. Classic features need no training: ORB finds corners in two images and matches them, enough to align, stitch or recognise a known part.
Predict first
Two boxes cover the same scratch, with confidence 0.91 and 0.84, overlapping by 80%. What should the output be?
Detectors propose several boxes per object. Non-maximum suppression keeps the most confident one and removes boxes that overlap it by more than the IoU limit, here 80% against a typical limit of 50–70%.
Live toy · quality inspection: a detector’s raw boxes, threshold and NMS
Boxes shown
–
Real defects found
–
False alarms and duplicates
–
Illustrative boxes drawn by the page, in the shape real detectors produce. YOLO26 (Ultralytics, January 2026) can also run without NMS in an end-to-end mode; the threshold choice stays yours.
Which tool on the line?
Classic vision (OpenCV, ORB)
Detector (YOLO)
Vision-language model
Labelled images needed
none: rules and reference images
a few hundred boxes per class
none
Speed per image
milliseconds on a CPU
milliseconds on a small GPU or edge box
about a second, through an API or a large GPU
Runs on the camera box
yes
yes (ONNX, TensorRT, OpenVINO)
rarely
Best for
alignment, measuring, known parts, barcodes
fixed defect classes at line speed
open questions, reports, rare cases, labelling data for the detector
The frameworks, in one map
PyTorch: where most research and nearly all LLM training happen; Hugging Face, vLLM and Ultralytics YOLO build on it.
TensorFlow and Keras: still in many production and mobile systems (TensorFlow Lite, now LiteRT). Keras 3 runs the same model code on JAX, TensorFlow or PyTorch.
JAX: Google’s array library for large-scale training on TPUs and GPUs.
ONNX: a common file format to move a trained model between frameworks and runtimes.
TensorRT, OpenVINO, Core ML: compile a model for NVIDIA, Intel or Apple hardware; often several times faster than running it in the training framework.
OpenCV and scikit-learn: classic vision and classic ML; no GPU needed.
TryTurn NMS off: every defect shows two or three boxes. Turn it back on and raise the IoU limit to 0.9: duplicates come back, because they no longer overlap “enough”. Lower the confidence threshold to 0.2: the faint dent is found, but so is a reflection. Find the setting that catches all three defects with no false alarm.
Common mistakeSending every frame from a production line to a vision-language model. At 10 frames per second that is 864,000 calls a day, each about a second long. Use a detector on the line and a VLM for the few uncertain cases, or to pre-label images for training the detector.
Essential takeawayFor fixed visual tasks at line speed, a detector such as YOLO with a tuned confidence threshold and NMS, or classic features such as ORB, beat a VLM on speed, cost and edge deployment. Train in PyTorch (or Keras), export through ONNX, compile with TensorRT or OpenVINO, and keep the VLM for open questions.
Text to query: the LLM writes the SQL, code checks it
LLMs are good at turning a question into SQL or an API call, and bad at knowing your schema’s quirks. A query is only useful if code checks it before it runs, and an eval set checks the answers.
Plain modeAn assistant fills in the library request slip for you. Before the librarian fetches anything, someone checks that the slip names real shelves and does not ask to empty the library.
Key ideaGive the model the schema and the definitions (what “revenue” means), let it write the query, then validate in code: it parses, is read-only, uses existing tables, columns and values, and has a row limit. Evaluate on question and answer pairs from your own data by comparing results (execution accuracy), not SQL text. A semantic layer of named metrics removes most errors.
Predict first
The generated SQL runs without an error and returns a number. Is the answer right?
A database checks syntax, not meaning. Forgetting to exclude cancelled orders still returns a clean number. Only a comparison with known answers catches it.
Live toy · an orders table, four questions, and the checks around the model
Result
–
Eval answer
–
Verdict
–
Simulated model outputs showing typical failure patterns; the results are computed from the table above. On the Spider 2.0 benchmark of real enterprise databases, an o1-preview agent solved 21.3% of tasks at publication, against 91.2% on the older, cleaner Spider 1.0.
TryAsk for German revenue with the definitions off: the query forgets to exclude cancelled orders and returns a believable wrong number that only the eval answer catches. Ask how many orders were cancelled with the schema off: “canceled” returns 0, and the validator spots a value that does not exist. Ask to delete test orders: the validator blocks it.
Common mistakeGiving the model a database user that can write, or trusting results because the query ran. Use a read-only role with a row limit and a timeout, and keep an eval set of questions with known answers.
Essential takeawayLet the LLM draft queries, and wrap it in code: schema and metric definitions in the prompt, a validator for read-only access, real tables, columns and values, and an eval set that compares results. The harder the schema, the more a semantic layer pays off.
Retrieval toolkit: BM25, vectors, hybrid, rerankers and graphs
RAG is only as good as what it retrieves. Keyword search, vector search and graphs each find different things; most good systems combine them and rerank.
Plain modeTo find a book you can search the exact title (keywords), ask for “something like this one” (vectors), or follow “same author, next in the series” (a graph). A good librarian uses all three.
Key ideaBM25 scores exact word matches and weights rare words more: unbeatable for codes, names and part numbers, and it needs no model. Vector search finds paraphrases through embeddings. Hybrid search runs both and merges the rankings, often with reciprocal rank fusion: each document scores 1 / (60 + rank) per list. A reranker reorders the top results. GraphRAG links entities so multi-hop questions can follow the links.
Predict first
A technician searches for the error code “E-4471”. Which retriever finds the right page most reliably?
A code has no meaning an embedding can capture, so “E-4471” and “E-4417” look alike to it. BM25 matches the exact string and rewards it for being rare.
Live toy · eight documents, three questions, five retrievers
Needed documents in the top 3
–
BM25 is computed live (k1 = 1.2, b = 0.75). The vectors come from a toy embedding that maps words to a few concepts, so paraphrases match and codes blur, as in real models. Reranker scores are illustrative. The graph was extracted by hand: Müller GmbH → order 5531 → warehouse Hamburg-Süd → team North.
Choices that matter more than the database
Chunking: split by headings and keep a title or short context with each chunk. Anthropic’s contextual retrieval test cut failed retrievals by 49% by adding context to chunks and combining embeddings with BM25, and by 67% with reranking on top.
Filters: product, language, date and access rights as metadata filters, before any similarity.
Graphs: worth their build cost for multi-hop questions and “what are the main themes across all documents”; Microsoft’s GraphRAG answers those from community summaries. For single-fact lookups, hybrid search is cheaper.
Measure retrieval alone: a list of questions with the documents that must be found, scored by recall@k, before you judge the generated answers.
Live toy · ten wrong answers: retrieval miss or generation miss?
TryAsk “E-4471” with vectors: the door-lock page with the similar code comes first. BM25 gets it right. Ask “my package never came”: BM25 has no shared words, vectors find the missing-delivery page. Hybrid gets both right. Ask the warehouse question: only the graph follows customer → order → warehouse → team.
Common mistakeUsing vector search alone. It misses exact codes, names and numbers, which are often what users type. Add BM25 and fuse the lists; it is cheap and usually the biggest single gain.
Essential takeawayBM25 finds exact terms, vectors find meaning, hybrid fusion gets both, a reranker fixes the order, and a graph follows links across documents. Measure retrieval on its own eval set, chunk with context, and filter by metadata first.
Changing a model directly: steering, editing and merging
Six places to intervene, from the prompt to every weight. The middle rungs are research tools worth understanding; for client work the rule stays the same: RAG for facts, LoRA for behaviour.
Plain modeYou can ask a singer to sing softer (prompt), turn a knob on the mixing desk during the song (steering), re-record one wrong word (editing), blend two recordings (merging), or send the singer to lessons (fine-tuning).
Key ideaConcepts such as tone or refusal often correspond to directions inside the model’s activations. Steering adds such a direction while the model runs; model editing rewrites a fact in a few MLP weights; merging combines fine-tunes by arithmetic on their weights.
Predict first
You add a “formal tone” direction to the activations, and keep making it stronger. What happens to the reply?
A small push moves the model along a meaningful direction. A big push throws the activations far outside anything seen in training, and the text turns into gibberish.
Live map · six ways to change what the model does, click a rung
Live toy · steer the customer reply along a “formality” direction
0
Illustrative, not a recorded run. Real steering (for example Anthropic’s “Golden Gate Claude” in 2024) shows the same pattern: moderate strength shifts the topic or tone, extreme strength breaks fluency. Try it on a real open model in Neuronpedia’s steering tool.
Live toy · where the steering direction comes from: mean of formal minus mean of casual
4
Run the model on formal and on casual versions of the same replies, read the activations at one layer, and subtract the two means: that vector is the direction. Shown in 2 of the 4,096 dimensions. More pairs average out what the sentences differ in by accident.
Live toy · logit lens: watch the guess form layer by layer
32
Reply to customer: “Your order ___”
The logit lens applies the final LM head to the residual stream of a middle layer. Illustrative values, not a recorded run, in the pattern real plots show: early layers guess generic tokens, the answer settles in the later layers.
The rungs convert into each other
Steering vector → weight edit.Steer2Edit (2026) turns a steering vector into small rank-1 edits of individual components, without fine-tuning, so the change ships inside the weights.
Two fine-tunes → a direction in weight space.Contrastive weight steering (Fierro and Roger) fine-tunes once towards a behaviour and once away from it, subtracts the two weight changes and adds or removes that difference.
Document → adapter.Doc-to-LoRA (Sakana AI, February 2026) is a hypernetwork: it writes a LoRA adapter for an unseen document or prompt in one forward pass, with no training run.
Context ↔ weights.Fast-Slow Training (2026) treats an optimised prompt as fast weights next to the slow model weights, and reports better sample efficiency and less forgetting than RL on the weights alone.
The ladder is a map of where a change lives, not a set of separate worlds. All of these need open weights.
Subliminal learning: a student trained on a teacher’s outputs can inherit the teacher’s traits through data that looks unrelated, when both share a base model (2025). Filtering the text does not remove it.
TryMove the steering slider to +3: the reply turns formal. At +9 it breaks. At −3 it turns casual. Then slide the logit lens from layer 0 to 32 and watch “has” and “is” take over from generic words.
Common mistakeUsing model editing to update business facts. Edits often fail on paraphrases and related facts, degrade the model after many edits and are hard to audit. Changing facts belong in RAG.
Essential takeawayYou can intervene at six levels: prompt, activation steering, targeted model editing (ROME, MEMIT), weight arithmetic (task vectors, TIES and DARE merging, abliteration), adapters, and full fine-tuning. Steering and merging are practical; direct fact editing is fragile. Research is moving toward models that update themselves (SEAL, Google’s Nested Learning), but none of it replaces RAG for facts and LoRA for behaviour today.
Beyond next-token prediction: JEPA, diffusion and other bets
Next-token training rewards the exact words, left to right. Some bets change what is predicted (JEPA predicts the representation of one view from another view), others the order of writing (diffusion fills a whole block in parallel). An honest contrast bench with a dated watch list, not a core module.
Plain modeShow a student half of a photo and ask her to describe what the hidden half is about, not to paint it pixel by pixel. She is graded on the idea, so small differences in wording or detail do not count against her.
Key ideaJEPA takes two views of the same thing (the visible and the hidden part of an image, a sentence and its code, two paraphrases), encodes both, and trains a predictor to produce the second view’s embedding from the first. The loss lives in embedding space, so it rewards predicting meaning, not exact pixels or words. The risk is collapse: if every input maps to the same vector, the loss is zero and nothing is learned. For language, LLM-JEPA adds this term on top of next-token loss and needs paired views, such as a request in text and the same request as code.
Predict first
The model writes “Your order is on its way.” The reference is “Your package has shipped.” Which loss punishes this more?
Next-token loss compares word by word, and almost every word differs. In embedding space the two sentences mean nearly the same thing, so the distance is small.
Live toy · one consequence: the model says “Your order is on its way.” Pick the reference answer
Illustrative values, not a recorded run. This toy shows a consequence of grading in embedding space (paraphrases are not punished), not the method itself: in a JEPA the target embedding comes from a target encoder, and a predictor learns to produce it from the other view. Next-token loss: average −ln p of the reference tokens under a model that prefers its own phrasing. Embedding distance: 1 − cosine similarity, as a meaning-trained objective would want it. Caution: many off-the-shelf sentence-embedding models put “shipped” and “cancelled” fairly close, because both sentences are about the same order; opposite meaning is exactly what generic embeddings often miss. Check with your own embedding model before relying on it.
How a JEPA is built · four parts, the loss lives in embedding space
No decoder turns the prediction back into pixels or tokens: the model is graded on meaning only. Fixes against collapse: a target encoder that is a slowly updated copy with a stop-gradient (I-JEPA, V-JEPA), variance and covariance penalties (VICReg), and LeJEPA’s SIGReg, which pushes the embeddings towards an isotropic Gaussian with a provable guarantee. LLM-JEPA adds this embedding loss on top of the usual next-token loss rather than replacing it. Where JEPA works today: video and images, for example V-JEPA 2.1 (Meta, March 2026).
Live toy · text diffusion: fill a whole canvas in parallel instead of left to right
3
Reply to customer: “___” · a canvas of 10 tokens
Model passes
0
Tokens fixed per pass
–
Reads as one sentence
–
Two good replies compete: “Your order is on its way and arrives Thursday.” and “Your order has shipped and should arrive on Thursday.” Each pass, the model scores every open position and fixes the confident ones; a position becomes confident once tokens of one reply are fixed elsewhere in the canvas, because every position sees the whole canvas. Masked diffusion can never undo a fixed token; DiffusionGemma-style noise lets low-confidence tokens be replaced in a later pass. Real models work on blocks of hundreds of tokens; this is a 10-token illustration. Why it can be fast: an autoregressive decode step leaves most of the GPU’s compute idle while it waits for memory (see Serving); a diffusion pass fills many positions with one read of the weights, which Google describes as moving DiffusionGemma from memory-bound to compute-bound. Image diffusion uses the same idea on pixels: see Image diffusion.
Watch list, November 2026 · bets beyond the plain transformer
Text diffusionearly products
Start from masked or random tokens and refine many positions in parallel, block by block. Examples: Inception’s Mercury models and Google’s open DiffusionGemma. Speed claims are mostly company-reported.
When it matters: single-user latency, editing and filling in text or code. Speed claims are not quality claims.
Hybrid linear attentionin production
Most layers use a fixed-size memory instead of a growing KV cache; a few full-attention layers remain. Examples: Kimi Linear, Qwen3-Next, NVIDIA Nemotron-H and Jamba, which mix Mamba-style or linear layers with attention.
When it matters: long context and many users, where the KV cache is the bottleneck (see Serving).
Sparse attentionin production
Each token attends only to the most relevant earlier tokens, picked by a cheap indexer, instead of all of them. DeepSeek introduced DeepSeek Sparse Attention with V3.2 to cut long-context cost.
When it matters: long documents and agents with long histories.
Tokenizer-free modelsresearch
Read raw bytes and learn the chunking instead of using a fixed tokenizer: H-Net (CMU and Cartesia) and Meta’s Byte Latent Transformer, which groups bytes into patches by how predictable they are.
When it matters: languages and data that tokenizers cut badly (see Tokens); robustness to typos.
Latent and recursive reasoningresearch
Think by looping hidden states instead of writing reasoning tokens. Recurrent-depth models repeat one block more often on harder problems; small recursive models such as the Tiny Recursive Model do well on puzzle tasks.
When it matters: test-time compute without longer outputs; for now mostly maths and puzzles.
Typed decision modelsearly products
Models that never write prose: they judge statements about a state and return a calibrated confidence for each, in a fixed format. Jev (TypeSafe AI, launched 15 September 2026) is the best-known; independent tests now exist, and open rebuilds read the same per-option probabilities from a small open model. See Encoders and embeddings.
When it matters: routing, classification and checks inside software, where an LLM’s prose is overhead.
JEPA and world modelsresearch
Predict the embedding of a hidden part instead of its tokens or pixels. V-JEPA 2.1 (Meta, March 2026) learns from video; LLM-JEPA adds an embedding loss to next-token training; VL-JEPA joins vision and language. AMI Labs raised funding in 2026 to build world models this way.
When it matters: robots, video and sensor data; for text models still a research add-on.
Multi-token predictionin production
Stays in token space: extra heads predict the next few tokens at each position. DeepSeek-V3 trains with it and reuses the extra head as a draft for speculative decoding.
When it matters: faster decoding; it belongs with speculative decoding on the Serving bench, not with JEPA.
Memory at test timeresearch
Layers that keep learning while the model reads: Titans and Google’s Nested Learning (Hope), and test-time training layers. See “Changing a model directly” for self-editing models such as SEAL.
When it matters: very long inputs and continual learning without retraining.
TryPick “Your package has shipped.”: high next-token loss, small embedding distance. Pick “Your order was cancelled.”: lower next-token loss but a large embedding distance, because the meaning is opposite. Switch the safeguard off: every distance becomes 0. In the diffusion toy, run masked diffusion with a pass budget of 1 or 2 a few times: uncertain tokens fixed in the same pass cannot agree, and the replies get mixed into nonsense. With a budget of 6, the first uncertain token decides the reply and the rest follow, so it usually finishes coherent in about 3 passes, against 10 for autoregressive. Re-noising repairs mixed tokens at the cost of an extra pass or two.
Common mistakeReading JEPA as a replacement for LLMs available today. It is a training objective under research, mostly aimed at world models from video and sensor data; chat models are still trained on next-token loss first.
Essential takeawayJEPA-style objectives score meaning by predicting embeddings and must prevent collapse. Text diffusion still predicts tokens but fills many positions per pass, trading some quality for speed: fixing too many tokens at once can produce incoherent text, so models use several refinement steps, blocks and, in some designs, re-noising. Hybrids, sparse attention, tokenizer-free and latent-reasoning models are the other bets; judge each on your eval set, not on a speed claim.
Images as tokens: a picture becomes a grid of patches
A vision model cuts an image into square patches and turns each patch into a vector, like a token. After that it is the same transformer you already know, and the cost question is the same too: how many tokens?
Plain modeCut a photo into stamps of the same size and describe each stamp with a list of numbers. The model reads the stamps in order, like words in a sentence. A bigger photo means more stamps to read, and a bigger bill.
Key ideaA vision transformer splits the image into patches (often 14 or 16 pixels square), flattens each patch, projects it to the model width and adds a position. A 224 × 224 image at 16 px is 14 × 14 = 196 patches. Tokens grow with the area: Claude counts ⌈width / 28⌉ × ⌈height / 28⌉ visual tokens, after shrinking images that are too large.
Predict first
You send a document scan at twice the width and twice the height. How many image tokens does it cost?
Patches tile the area. Twice as many along each side is four times as many patches, until the model’s size limit shrinks the image.
Live toy · how many tokens does this image cost?
Size the model sees
–
Visual tokens
–
1,000 images on Sonnet 5.5
–
Rules from Anthropic’s vision docs, November 2026: 28 × 28-pixel visual tokens; Claude 4.7 and later shrink images to at most 2,576 px on the long edge and 4,784 tokens, older models to 1,568 px and 1,568 tokens. Gemini instead counts 258 tokens per image up to 384 px, and per 768 × 768 tile above that. A classic ViT first resizes every image to its fixed input, here 224 × 224.
TryPick the phone photo: it is shrunk to the size limit, so a 12-megapixel photo costs no more than a large screenshot. Then pick the A4 scan and halve both sides: a quarter of the tokens. Switch to the older Claude models and watch small print drop below one patch.
Common mistakeSending whole high-resolution pages when the answer sits in one table. Cost grows with the area: crop to the region first. The opposite mistake is shrinking too far: if a character is smaller than a patch, OCR-style questions fail. Test at the resolution you will really send.
Essential takeawayImages become patches, patches become vectors, and the transformer reads them like tokens. Cost and context use grow with the area up to the model’s size limit, so crop, pick the resolution on purpose, and count image tokens in your budget like text.
Image diffusion: train by adding noise, generate by removing it
Image generators start from pure noise and remove a little of it at every step, steered by the prompt. They learn this the other way round: add noise to real images and learn to predict it.
Plain modeShow a child a drawing covered in more and more sand, and ask each time: where is the sand? After thousands of drawings the child can start from a pile of sand, brush a little away at a time, and a drawing appears.
Key ideaTraining: take an image, add noise of a random strength, and train a network to predict that noise, or in flow matching (Stable Diffusion 3, FLUX) the direction back to the image. Generation: start from noise and take 20–50 steps. Latent diffusion does this in a compressed space: a VAE turns 512 × 512 × 3 pixels into 64 × 64 × 4 numbers, 48× fewer. Guidance pushes the prediction towards the prompt.
Predict first
You raise the guidance scale from 7 to 20. What happens to the picture?
Guidance extrapolates from the unprompted towards the prompted prediction. A little sharpens prompt match; a lot overshoots, with oversaturated colours and burnt-in detail.
Live toy · prompt: “a red parcel on a green lawn under a blue sky”
What the network predicts at this step
Network passes
–
Prompt match
–
Artefacts
–
Illustrative 48 × 48 picture, drawn by the page, not a real model. Real models run in a latent space and need one network pass per step, or two with guidance (prompted and unprompted), unless the two are batched or distilled into one.
Same training ideas, new outputs
Fine-tuning: a LoRA on 10–30 photos teaches a product, a face or a style (DreamBooth, LoRA): the same low-rank trick as on the LoRA bench.
Control: extra inputs such as an edge map, a pose or a depth map fix the layout (ControlNet), so the prompt only fills in the look.
Speed: distilled models generate in 1–4 steps instead of 30, the image counterpart of distillation for LLMs.
Video: the same denoising over a stack of frames in a video latent; consistency across frames is the hard part.
Other route: some newer generators write images as discrete tokens, one after another, like text; text diffusion goes the other way and brings this bench’s idea to language (see Beyond next-token).
TryIn training mode, slide progress from 0 to 100: the parcel disappears into noise, which is exactly what the network learns to undo. In generation mode, drop the steps to 4: blotchy and unfinished. Push guidance to 20: the parcel is unmistakable but the colours burn; at 1 the scene drifts away from the prompt.
Common mistakeFixing a bad picture with more steps or more guidance. Beyond about 30 steps little changes, and high guidance trades realism for prompt match. Better prompts, a LoRA or a control input usually fix what steps cannot.
Essential takeawayDiffusion models learn to predict noise (or the way back to the image) at every noise level, then generate by denoising from pure noise in 20–50 steps, in a compressed latent space. Guidance trades realism for prompt match, LoRA and control inputs adapt the model, and distillation cuts the steps.
Vision-language models: how a chat model learns to see
First, contrastive training puts images and captions into one shared space. Then a vision encoder is joined to an LLM through a small projector, so image patches arrive as extra tokens next to the text.
Plain modeFirst a translator learns which picture goes with which sentence. Then the translator sits next to a writer and whispers what is in the picture, in words the writer understands.
Key ideaCLIP learns from image and caption pairs with the contrastive loss from the Encoders bench: in each batch, every image must score its own caption highest. A VLM (LLaVA-style) passes the vision encoder’s patch vectors through a projector, a small MLP, into the LLM’s token space. Stage 1 trains only the projector on captions; stage 2 fine-tunes projector and LLM on visual instructions.
Predict first
In stage 1 of LLaVA-style training, which part is trained?
Encoder and LLM are both frozen. Only the projector learns to translate patch vectors into something the LLM reads like word vectors. That is cheap and keeps both models’ skills intact.
Live toy · a CLIP training batch: four images, four captions
Contrastive loss
–
Images matched correctly
–
Illustrative similarities. The loss is the average of −ln (softmax of each row at its own caption): the diagonal should win every row. The original CLIP trained on 400 million pairs with batches of 32,768, so each image had 32,767 wrong captions to beat.
Live map · what is trained in each stage, click a stage
Sizes for a typical open VLM: a CLIP ViT-L/14 encoder (about 300 M parameters), a two-layer MLP projector from 1,024 to 4,096 dimensions (about 21 M), and a 7B LLM.
TryMove the training steps from 0 to 10: the diagonal turns green and the loss falls. At step 2, “a parcel at the door” and “a delivery van” still compete for the van image. In the stage map, compare how many parameters are trained in each stage.
Common mistakeAssuming a VLM reads text in images as well as a plain text input. Small print is cut into patches and shrunk with the image; for documents, extract the text first when you can, or send the page at the resolution that keeps characters larger than a patch.
Essential takeawayVLMs reuse two trained parts: a vision encoder made by contrastive image–text training and an LLM, joined by a small projector. Training goes from cheap alignment (projector only) to visual instruction tuning, and you adapt one with LoRA like any other LLM.
Speech becomes a spectrogram or a stream of discrete audio tokens, and video becomes frames of patches. Every time, the practical question is the same: how many tokens per second, and does it fit the context?
Plain modeSound is turned into a picture of which pitches are loud at each moment, and video into a flip-book of photos. Then the model reads them like it reads words, and a long recording is a very long book.
Key ideaWhisper turns 30 seconds of audio into a log-mel spectrogram of 3,000 frames (one every 10 ms); its encoder halves that to 1,500 vectors and a decoder writes the text. Speech generation uses a neural audio codec that turns sound into discrete tokens at a fixed rate, so an LLM can predict audio like text. Video is frames × patches: Gemini counts about 263 tokens per second of video and 32 per second of audio.
Predict first
A one-hour meeting recording goes to a model that counts 32 tokens per second of audio. About how many tokens is that?
3,600 seconds × 32 = 115,200 tokens: one hour fits a 200k context, while the same hour as video at 263 tokens per second (about 950,000) only fits a 1M context.
Live toy · token budget for audio and video
Tokens
–
Fits a 200k context
–
Fits a 1M context
–
Rates: Gemini API token counting (32 tokens per second of audio, about 263 per second of video); Whisper encoder 50 vectors per second; Kyutai’s Mimi codec 12.5 frames per second × 8 codebooks; EnCodec at 24 kHz 75 frames per second × 8 codebooks; frames sent as images at about 1,300 Claude visual tokens each (1,000 × 1,000 px). Check your model’s own rules.
Live toy · a spectrogram: how speech becomes frames
Synthetic spectrogram of a 1.5-second phrase: time runs left to right, pitch bottom to top, brightness is loudness.
TryPick “Meeting audio” and slide to one hour: about 115,000 tokens. Switch to “Video, Gemini”: the same hour no longer fits 200k. For “Video as images”, drop the sampling to one frame every 5 seconds: most meetings lose nothing, and the cost falls by 10× against 2 frames per second.
Common mistakeSending a long video when the question is about what was said. Transcribe the audio first (far fewer tokens), and add a few frames only where the picture matters.
Essential takeawayAudio turns into spectrogram frames or codec tokens, video into frames of patches, and each has a token rate. Multiply the rate by the length before choosing a model, sample frames on purpose, and transcribe when only the words matter.
Customer cases: choose the route, price it, size it
Short, made-up customer situations like the ones in real projects. Answer each question, then read why and follow the link to the bench. The cases match your track; pick another track at the top to see its cases. Your answers are saved in this browser and in your progress file.
Next steps
How to learn this: eight steps, each with a build
Reading alone does not stick. Each step has one thing to build and a few links to read while you build it. About ten weeks at a few evenings a week, or two weeks full-time (see below). The eval set comes first, because every later step is measured on it.
Plain modeLearning this is like learning a sport: watch a little, practise one move, then play a real match. Each step below has one small match to play.
1
Your eval set and the training loop
week 1
Do: Write 50–100 real questions from your field with checked answers: your eval set from day one. Then write micrograd and the five-line PyTorch training step from memory.
Do: Run GRPO on GSM8K with a 0.5–1.5B instruct model in TRL. Plot reward and accuracy, then weaken the checker on purpose and watch reward hacking happen.
Do: Steer a small open model with a direction you compute yourself (mean of formal minus mean of casual activations), then merge two LoRA adapters you trained in step 3 and run both eval sets on the result.
Days 1–2: eval set, then the training loop (steps 1 and 2 from Karpathy’s lessons, without building a full GPT).
Days 3–5: SFT and LoRA on your own data, with the eval set as the gate (step 3).
Days 6–7: DPO or distillation, whichever your project needs (step 4).
Day 8: the verifier ladder: checker at answer time, then best of n (step 5, without full RL).
Days 9–10: quantize and serve it with vLLM, measure at 1, 8 and 32 users (step 6). Steering and merging in an afternoon if time is left (step 7). Ship behind the eval gate (step 8).
Or the whole pipeline at once: Karpathy’s nanochat runs tokenizer, pre-training, SFT, RL and a chat UI end to end on one GPU node: the same order as this path.
How to work
Start on one GPU. A free Colab or Kaggle notebook is enough for steps 1 and 2. A single 24 GB GPU (for example an AWS g5 instance) runs QLoRA on a 7–8B model.
Make your eval set on day one. 50–100 real questions from your field, with answers checked by hand. Every later step is measured on it.
Run it as published, then change one thing. First reproduce a notebook exactly, then swap in your data, then one setting at a time.
Write a short note after each step. If you cannot explain it in five sentences, go back. Rate the matching glossary terms below as you go.
Go further
Go further: interactive tools and courses
This page is a study bench. These are the best places to see the same ideas in real models and to keep improving, in one list.
Not about LLMs: an essay with review questions built in and spaced repetition afterwards.
Best for: The method behind this page’s “Review”: retrieval beats rereading.
A good rhythm: one lesson or video, then build the matching step of the learning path, then run “Review” in the glossary for a few minutes. Retrieval practice beats rereading.
Keep going · Facts that change
Facts that change, and when they were last checked
Prices, model rules and terms change every few months. These are the facts the benches depend on, when they were last checked and where to check them. A scheduled check compares every row with its source on the 1st of each month and reports what changed; when a row changes, update the bench and the date here.
Last checked · 22 November 2026
Fact
What the page uses
Where
Check at
Claude API prices
Per million input / output tokens: Fable 5.2 $8 / $40, Opus 5.5 $4 / $20, Sonnet 5.5 $2 / $10, Haiku 5.5 $0.10 / $0.50 (higher above 100k-token prompts); 5-minute cache write 1.25× input; cache reads 0.05× input on Sonnet and Opus 5.5 ($0.10 and $0.20), 0.025× on Fable 5.2 ($0.20), 0.1× on Haiku 5.5
Rate each term honestly; ratings stay in this browser. Filter to the weak ones and answer the check question out loud. “read ↗” opens a primary source; the learning path above puts them in order.
Sort it · parameter, hyperparameter or generation setting?
Parameterlearned by trainingchanges a little at every optimizer step
Hyperparameterchosen by you before trainingwritten in the config, never learned
Generation settingchosen when the model answerschanges how tokens are picked, not the model
Your progress file · shared with the LLM Lab tutor
Ratings, review boxes and your predictions stay in this browser. Copy them as a progress file for the tutor skill in any agent, or paste the file your tutor keeps to see what it thinks you are missing.