Breadth: LLM pretraining, scaling laws, fine-tuning with LoRA, RLHF, DPO and evals
Before this lesson: lesson 07 (the training step, the 16 bytes per parameter of mixed-precision Adam, BPE) and lesson 08 (the decoder and its sampling). Background: KL divergence and cross-entropy in the Information Theory track, LoRA as low rank in the Linear Algebra track, and policy gradients and PPO in the Reinforcement Learning track. A full LLM course (see the resources) treats every topic here in full depth. Time: about 90 minutes, plus the notebook.
Why this matters #
LLM questions are now standard breadth in ML engineer, research engineer and research scientist interviews, not a specialty. A common opening is "Walk me through how a chat model is trained." A strong answer names the stages in order, gives one equation and one trade-off per stage, and uses numbers: tokens, FLOPs, GPU-hours. A weak answer lists method names. The same questions come back in daily work and in ML for science: how large should a foundation model be for my data and my compute? Should I fine-tune on labels or with a reward from a checker? Is the new model better, or did the number only move inside its error bar?
1. Predict first #
2. The picture #
Start with the simplest model. A language model gives a probability to each possible next token. A model that knows nothing spreads the probability evenly over the vocabulary of tokens. Its loss per token is then , which is nats for . The perplexity is , here exactly : the model is as unsure as a choice among equal options. Every stage of training removes uncertainty in a different way.
| Stage | Data | Training signal | What it adds |
|---|---|---|---|
| Pretraining | – tokens of filtered, deduplicated web text, code, books | next-token cross-entropy | knowledge, language, in-context learning |
| Mid-training | a smaller high-quality mix (math, code, long documents) while the learning rate decays | the same loss | quality, skills, long context |
| SFT | – (prompt, response) demonstrations | cross-entropy on response tokens only | the format: follow instructions, chat template, tool calls |
| Preference tuning | pairs (chosen, rejected) | reward model + PPO, or DPO | which of the possible answers people prefer |
| RL with verifiable rewards | prompts with a checker (a math answer, unit tests) | reward 1 if correct, else 0 | reasoning: longer, self-checking solutions |
| Evaluation | held-out benchmarks, human or model judges | — | the decision whether a change helped |
In one line: pretraining makes the model know; SFT makes it answer in the right form; preference tuning chooses among good answers; RL with a checker makes it search for correct answers. Evaluation decides at every step.
Scaling in one picture. For a fixed compute budget, model size and data trade against each other. You can train a big model on few tokens, or a small model on many tokens. Along this line of equal compute (an iso-FLOP curve) the final loss is U-shaped. The bottom of the U is the compute-optimal model. The bottom is flat: a model 2× smaller or larger loses very little.
Move the model size along one budget. The blue curve is the Chinchilla loss fit with tokens, so every point costs the same compute . The orange dot is the minimum of the fit, and the aqua dot is the "20 tokens per parameter" rule. The preset is predict question 1: 10 B parameters on 20 B tokens. Notice how far up the U it sits, and how flat the bottom is.
A model with B parameters is trained on B tokens. About how many FLOPs does training cost?
. The option counts only the forward pass ( per token); the backward pass costs another per token. Section 3.2 derives the factor 6.
Post-training in one picture: the KL leash. Take one prompt with two possible answers. The SFT model gives each answer probability . A reward model scores them and . We want a new policy with a high expected reward, but every nat of KL divergence from costs . For the best policy is (section 3.6 derives it). As it puts all mass on the higher reward; as it stays at . So is the length of the leash that ties the policy to .
Shorten and lengthen the leash with . Faint blue bars are the reference policy ; solid orange bars are the optimal policy . Edit the rewards and the reference probabilities. Try "reward hack": one answer has a high proxy reward but a tiny reference probability. Watch how small must be before moves to it, and how large the KL becomes.
In the two-answer toy (, rewards ), you halve from to . What is the new probability of the better answer?
. With the weights are and , so the better answer gets . A smaller is a longer leash, but the policy reaches only in the limit . The value belongs to .
3. Definitions and main results #
Notation. is the number of parameters, the number of training tokens, the training compute in FLOPs, the vocabulary size, the sequence length. is the probability that the model with parameters gives the response to the prompt .
3.1 Pretraining loss, perplexity, bits per byte #
The text is a sequence of tokens . The pretraining loss is the average negative log-probability of each token given the tokens before it:
Minimizing it is maximum likelihood. It is the cross-entropy between the text and the model. In expectation it equals the entropy rate of the text plus a KL divergence, which is never negative. So the loss cannot go below the entropy of the text.
- Perplexity is (with in nats). It depends on the tokenizer: a tokenizer with longer tokens has fewer, harder predictions. So perplexity compares only models with the same tokenizer.
- Bits per byte divides the total loss by the number of bytes of the text: . It does not depend on the tokenizer, so it compares models with different tokenizers.
The data pipeline matters as much as the model: extract text from HTML, keep the wanted languages, filter by quality (rules and a classifier), remove exact and near duplicates (MinHash), choose a mixture weight for each source, and remove benchmark test items (decontamination).
3.2 Compute: #
Claim. Training a dense transformer with parameters on tokens costs about floating-point operations (FLOPs).
- Almost all FLOPs are products with weight matrices. A weight matrix of size applied to one token's vector costs multiplications and additions: FLOPs. Summed over all matrices: FLOPs per token in the forward pass.
- For the backward pass computes two products of the same size: the gradient for the input, ( FLOPs), and the gradient for the weights, ( FLOPs). So per token.
- Total per token, so .
What the count leaves out: the attention scores and their weighted sums (Kaplan et al. show that this extra cost is small while the context length is below about ), activation recomputation (it repeats the forward pass: instead of per token), and the embedding lookup (no matrix product). Inference costs about FLOPs per generated token.
From FLOPs to time. Time , with the peak FLOP/s of one GPU. MFU (model FLOPs utilization) is the fraction of the peak that the model's FLOPs really use. Large tuned runs reach about 40%: the Llama 3 report gives 38–43% bf16 MFU.
Memory. Mixed-precision training with Adam stores about 16 bytes per parameter: bf16 weights (2) and gradients (2), plus fp32 master weights, first moment and second moment (12). This is the count of the ZeRO paper (lesson 07). Activations come on top. A 7 B model needs GB for these states alone, more than one 80 GB GPU, so the states must be sharded (lesson 12).
3.3 Scaling laws #
Kaplan et al. (2020) found smooth power laws of the loss in , and . Their compute-optimal model size grew as : "make models bigger, and train them on relatively few tokens".
Chinchilla (Hoffmann et al., 2022) fitted a different form:
is the irreducible loss (the entropy of text), is the cost of a finite model, and is the cost of finite data. (Here is an exponent; it is not the of RLHF.)
Theorem (compute-optimal allocation). Minimize subject to . The minimum is at
Why this is true, in one sentence. Growing lowers the model term but, at fixed compute, shrinks and raises the data term; the best point balances the two rates of change.
- Substitute : .
- Set the derivative to zero: .
- Multiply by and use : . At the optimum the model term and the data term are in the fixed ratio .
- From step 2, . Take the power to get ; then gives the second formula.
- It is a minimum: with , the two terms and are convex in , so their sum has exactly one stationary point, and it is the minimum.
Because , both exponents are near : grow and by the same factor. The paper's three methods give –; the rounded constants above give . The practical rule is about 20 tokens per parameter. Chinchilla itself (70 B parameters, 1.4 T tokens) used about the compute of Gopher (280 B parameters, 300 B tokens) and beat it. With we get , so .
Why Kaplan differs (Chinchilla §2): Kaplan used one learning-rate schedule and one token count for all runs. The losses of shorter runs were read from checkpoints of a long cosine schedule, so they were too high. This undervalued data. Most of Kaplan's models were also small.
Why practice "over-trains". Chinchilla minimizes training compute only. Serving costs FLOPs per generated token, for the whole life of the model. So a smaller model trained on many more tokens is cheaper overall. Llama 3 8B saw about 15 T tokens: about 1,900 tokens per parameter. The flat bottom of the iso-FLOP curve makes this cheap (section 4).
3.4 Supervised fine-tuning (SFT) #
Each example is a prompt and a response , written into one token sequence by a chat template (special tokens mark the roles and the end of a turn). With a mask on response tokens and on prompt tokens:
Trade-offs. SFT is cheap, stable, and uses the same code as pretraining. But it only imitates. The model cannot beat its demonstrations, and it never sees what not to do. Demonstrations of facts the model does not know can teach it to make things up (Gekhman et al., 2024).
3.5 LoRA: fine-tuning a low-rank correction #
Full fine-tuning changes a weight matrix into , and it needs gradients and Adam states for every weight. LoRA (Hu et al., 2021) assumes that a useful has low rank.
Definition. A frozen pretrained weight maps an input to . LoRA adds a trainable low-rank path:
The input is squeezed to numbers () and expanded back (). The update is a sum of rank-1 matrices, so its rank is at most (Linear Algebra lesson 15).
- Parameters: instead of . For and : instead of , which is .
- Initialization: random (Gaussian), . So , and training starts exactly at the pretrained model.
- Scale: lets you change without retuning the learning rate much. (rsLoRA uses for large .)
- Merge for inference: is one matrix again, so a merged LoRA adds no latency.
- In code, compute for a batch of row vectors. Never build the matrix in the training forward pass.
Choose the rank budget . The target update (left) and its best rank- approximation . Move and watch the error and the parameter count against . When the singular values decay fast, a small already captures most of ; this is the bet that LoRA makes.
Theorem (LoRA gradients). Let and let be the gradient that arrives from the layers above. Then
- . is frozen, so only the term depends on and .
- For fixed , is linear in : . So , which is the matrix .
- The gradient with respect to is (the transpose of the linear map , applied to ).
- is linear in , so by the argument of step 2, .
Consequences for the initialization.
- With : , but . So moves first. After one step , and then moves too.
- With : both gradients are zero at every step. Nothing trains.
- With both random: at step 0. Training starts from a changed, worse model.
- with random also works (the mirror case). What matters is with not both factors zero.
What LoRA saves, and what it does not.
- Saves: the gradients and optimizer states of . Full fine-tuning with Adam needs about 16 bytes per parameter. LoRA needs the frozen weights (2 bytes per parameter in bf16) plus about 16 bytes per adapter parameter. Hu et al. report 1.2 TB → 350 GB of GPU memory for GPT-3 175B, and a checkpoint of 35 MB instead of 350 GB (, query and value projections only).
- Does not save: activations. Backpropagation still needs the stored inputs of every adapted layer, and the gradient must still flow through every frozen to the layers below. The backward pass skips only the weight gradient of (the paper reports a 25% speed-up).
- Capacity: each adapted matrix can change only by a matrix of rank at most . For a large domain shift (a new language, continued pretraining) LoRA can fall short of full fine-tuning; it also forgets less of what the base model knew (Biderman et al., 2024).
- QLoRA (Dettmers et al., 2023) stores the frozen base in 4-bit NF4 and puts adapters on all linear layers; this fine-tunes a 65 B model on one 48 GB GPU.
A colleague initializes a LoRA layer with and "to start exactly at the pretrained model". What happens in training?
because , and because . Both stay zero, so no step ever moves them. The paper's choice ( random, ) also gives , but .
3.6 Reward model and RLHF with PPO #
Reward model. Labelers choose the better of two responses: (winner) and (loser). The Bradley–Terry model says
with the logistic function and a scalar head on an LLM. The loss is : logistic regression on the difference of two scores. Only differences matter, so is fixed only up to a constant for each prompt.
RL objective. With the SFT model and :
Theorem (optimal policy). For each prompt the maximizer is
Why this is true, in one sentence. The objective is, up to a constant, minus times the KL divergence from to , and a KL divergence is smallest (zero) when the two distributions are equal.
- Fix and drop it from the notation. The objective is .
- Take the log of the definition of and solve for the reward: .
- Substitute this into . The two terms cancel, and : .
- does not depend on , and with equality only at . So is the unique maximizer, and the maximum value is .
In the toy of section 2: , so .
PPO in practice (InstructGPT): sample responses from the policy, score them with , add a KL penalty per token, estimate advantages with a value model and GAE, and update with the clipped probability ratio. Four models are in memory: policy, reference, reward model, value model.
Trade-offs. PPO learns from its own samples, so it can improve beyond the data. But it is expensive (generation inside the training loop), has many hyperparameters, and can be unstable. And the reward model is only a proxy. Gao et al. (2022) showed that the true reward first rises and then falls as the policy moves further (in KL) from . This is reward over-optimization (also called reward hacking).
3.7 DPO: the reward model inside the policy #
Step 2 of the proof writes the reward through the optimal policy. DPO (Rafailov et al., 2023) puts this expression into the Bradley–Terry model:
- . The term cancels, because both responses answer the same prompt .
- Replace the unknown by the trained policy , and minimize the Bradley–Terry loss on the preference pairs:
The implicit reward is . The gradient is
It raises the log-probability of the winner, lowers that of the loser, and the weight is large when the model still ranks the pair wrongly.
DPO needs two models (the policy and the frozen reference), no sampling, and the training loop of SFT. Trade-offs: it is offline. It learns only from the fixed pairs, often sampled from other models, so it cannot explore or get feedback on its own new answers. It can overfit the pairs, and it can lower the likelihood of both responses. Variants: IPO (a squared loss against overfitting), KTO (unpaired thumbs up or down; still uses ), SimPO and ORPO (no reference model).
3.8 RL with verifiable rewards and GRPO #
For math and code, a program can check the answer. The reward is if the final answer matches or the unit tests pass, else (sometimes plus a small format reward). GRPO (DeepSeekMath, 2024) samples a group of responses for each prompt and gives every token of response the advantage
The group mean replaces the value model as the baseline: an answer is good if it beats the other answers to the same prompt. The update is a PPO-style clipped ratio per token, plus a KL term to . DeepSeek-R1-Zero ran this on a base model with only accuracy and format rewards; its responses grew longer, and it learned to re-check its own steps.
Click an answer to flip its reward between 1 (correct) and 0 (wrong). The bars are the advantages: blue pushes the answer up, orange pushes it down. Make all answers correct (or all wrong): every advantage becomes 0, and the prompt gives no learning signal. Switch to "no std" (Dr. GRPO) to see that only the scale changes.
Trade-offs. It works only where a checker exists. Generation dominates the cost. A group where all answers get the same reward has zero advantage and gives no signal (DAPO filters such groups and samples new prompts). The checker can be gamed. Variants: Dr. GRPO removes the length and std normalizations, because they bias the update; DAPO drops the KL term. It is still debated whether this RL teaches new abilities or mainly makes the model sample its best answers more often (higher pass@1, similar pass@ for large ).
Other tools of the same stack: rejection-sampling fine-tuning (sample many answers, keep the best, run SFT on them), distillation (SFT on a stronger model's outputs), and RLAIF (AI feedback instead of human labels).
| Method | Data | Models in memory | Online | Strength | Main failure mode |
|---|---|---|---|---|---|
| SFT | demonstrations | 1 | no | simple, stable; sets the format | imitation only; no negative signal |
| RLHF (PPO) | pairs → reward model; prompts | 4: policy, reference, reward, value | yes | can go beyond the data; any learned reward | cost, instability, reward hacking |
| DPO | pairs | 2: policy, reference | no | as simple as SFT; no reward model | off-policy; overfits; no exploration |
| GRPO + checker | prompts + a checker | policy + reference (1 without the KL term) | yes | strong for math and code reasoning | only checkable tasks; zero-signal groups |
Your team has 50,000 preference pairs, little GPU budget, and wants simple, stable code. Which method fits, and what is its main limit?
DPO trains on fixed pairs with the SFT loop and two models, so it is cheap and stable. Its price is that it is offline: it never gets feedback on its own new answers. PPO needs four models and generation in the loop. GRPO needs a checker, which preference pairs do not give. DPO has no separate reward model: the reward is implicit in the policy.
3.9 Evaluation #
- Perplexity and bits per byte measure language-modeling quality, not usefulness. Compare perplexity only between models with the same tokenizer.
- Benchmarks: multiple choice (MMLU), scored by the log-likelihood of each option or by the generated letter; generative tasks (GSM8K, HumanEval), scored by a checker. An accuracy on independent questions has standard error .
- pass@ (Chen et al., 2021) is the probability that at least one of samples is correct.
- LLM-as-judge is cheap and scales, but it prefers the first position, longer answers, and its own outputs (Zheng et al., 2023). Mitigate: swap the order and average, control for length, use a judge from a different model family, and check agreement with human labels.
- Contamination: test items inside the training data inflate scores. Detect it with -gram overlap (GPT-3 used 13-grams), report results on a clean subset, and prefer new or private test sets.
Theorem (unbiased pass@). Draw independent samples for one problem, and let of them be correct. Then
is unbiased for , where is the probability that one sample is correct. The plug-in estimate is biased low.
- is the probability that a random subset of of the samples contains no correct sample.
- Average this over the random samples. A random -subset of independent samples is itself independent samples, so its chance to be all wrong is . Hence , and the estimator is unbiased.
- The plug-in uses with . The function is concave, so by Jensen's inequality : it is too low on average.
Change , and . The blue curve is the unbiased estimator for every , and the orange curve is the plug-in . At they agree. For larger the plug-in is lower, and at the unbiased estimator is exactly 1 whenever .
A model scores 70% on a benchmark of 1,000 independent questions. What is the standard error of this accuracy, in percentage points?
, so 1.4 points. A 95% interval is about points (1.96 standard errors), so a new model at 71.5% is not clearly better. The option 0.02 forgets the square root ( is the variance), and 4.6 is the standard error for only 100 questions.
Answers to section 1. (1) It is 2 tokens per parameter, far from about 20. The budget is FLOPs. With : B and B tokens. The Chinchilla fit gives a loss of for the plan and for the 20-tokens choice (its own minimum, , is at 2.0 B parameters on 101 B tokens). If the model will serve many tokens, go even smaller and train longer. (2) DPO learns only from a fixed set of pairs. Online RL samples from the current policy and gets a reward for exactly those samples. So it can explore, it can improve beyond the data, and it can use a checker. The price is cost and instability.
4. Worked example #
A. Plan a small pretraining run. The budget is 8 H100 GPUs for 24 hours. Peak dense bf16 throughput is TFLOP/s per GPU. Assume 40% MFU, so each GPU gives useful FLOP/s.
- Compute: FLOPs.
- Chinchilla rule: parameters, and B tokens.
- Memory: GB for weights, gradients and Adam states. It fits on one 80 GB GPU with room for activations, so plain data parallelism works.
- Serving cost: GFLOP per generated token.
- Over-trained option: B on B tokens (182 tokens per parameter). With the Chinchilla fit, the loss rises only from to nats (), and every generated token costs 3× less.
B. One DPO pair. . The sequence log-probabilities are , , , .
- Implicit rewards: and .
- Margin: .
- Loss: .
- Gradient weight: . The pair still gets a large update, because the policy separates the two responses only a little.
C. One GRPO group. answers to one math prompt, with rewards .
- Mean: .
- Standard deviation (population, divide by ): . (For 0/1 rewards with mean , the variance is .)
- Advantages: for each correct answer and for each wrong one.
- If all 8 were correct, every would be : no signal. Implementations add a small to the std to avoid . Some libraries divide by in the std; this multiplies all advantages by the same factor .
D. Is model B better? Model A scores 71.0% and model B 72.5% on the same 1,000 questions.
- Each standard error is about points.
- If we treat the two scores as independent, the difference has standard error points, so the 95% interval is points. Not significant.
- A paired test on the same questions is tighter, because it removes the variation in question difficulty. Report the interval either way.
E. pass@. samples, correct.
- pass@1 .
- pass@5 .
- The plug-in gives : too low.
F. LoRA on a 7 B model. A Llama-2-7B-shaped model has 32 layers, width and full multi-head attention, so are all . LoRA with on these four:
- Per matrix: . Per layer: .
- All layers: trainable parameters, about of 7 B.
- Their training states: MB. The frozen base: GB in bf16.
- Full fine-tuning would need GB for the same states.
5. In code #
First, a check of forward and backward FLOPs per token, with PyTorch's FLOP counter on a stack of bias-free linear layers (as in modern LLMs):
import torch
from torch.utils.flop_counter import FlopCounterMode
torch.manual_seed(0)
d, T = 64, 128 # width, tokens in the batch
model = torch.nn.Sequential( # 4 bias-free linear layers
torch.nn.Linear(d, 4 * d, bias=False), torch.nn.GELU(),
torch.nn.Linear(4 * d, d, bias=False),
torch.nn.Linear(d, 4 * d, bias=False), torch.nn.GELU(),
torch.nn.Linear(4 * d, d, bias=False),
)
N = sum(p.numel() for p in model.parameters())
x = torch.randn(T, d, requires_grad=True) # as for a layer deep inside a network
with FlopCounterMode(display=False) as fwd:
y = model(x)
with FlopCounterMode(display=False) as bwd:
y.square().mean().backward()
print(N, fwd.get_total_flops() / (N * T), bwd.get_total_flops() / (N * T)) # 65536 2.0 4.0
With requires_grad=False on x, the backward ratio drops to 3.5: the first layer needs no
gradient for its input.
Second, the closed form of section 3.3 against a numerical minimizer, and the other numbers of section 4, in NumPy:
import numpy as np
from math import comb
from scipy.optimize import minimize_scalar
E, A, B, alpha, beta = 1.69, 406.4, 410.7, 0.34, 0.28 # Hoffmann et al. (2022), approach 3
C = 2.73e20 # the budget of section 4A
def loss_on_isoflop(logN): # D is fixed by C = 6ND
N = np.exp(logN)
return E + A / N**alpha + B / (C / (6 * N))**beta
res = minimize_scalar(loss_on_isoflop, bounds=(np.log(1e7), np.log(1e12)), method="bounded")
G = (alpha * A / (beta * B)) ** (1 / (alpha + beta))
print(f"{np.exp(res.x):.3e} {G * (C / 6) ** (beta / (alpha + beta)):.3e}")
# 1.016e+09 1.016e+09
for N in [0.5e9, 1e9, 1.5e9]:
print(f"N = {N:.1e} D/N = {C / (6 * N) / N:5.1f} L = {loss_on_isoflop(np.log(N)):.3f}")
# N = 5.0e+08 D/N = 182.3 L = 2.489
# N = 1.0e+09 D/N = 45.6 L = 2.470
# N = 1.5e+09 D/N = 20.3 L = 2.475
p = np.array([0.5, 0.5]) * np.exp(np.array([1.0, 0.0]) / 1.0) # KL leash, beta = 1
print((p / p.sum()).round(3)) # [0.731 0.269]
sig = lambda z: 1 / (1 + np.exp(-z)) # DPO pair of section 4B
rw, rl = 0.1 * (-10 + 12), 0.1 * (-15 + 14)
print(round(-np.log(sig(rw - rl)), 3), round(sig(rl - rw), 3)) # 0.554 0.426
r = np.array([1, 0, 0, 1, 1, 0, 0, 0], float) # GRPO group of section 4C
print(((r - r.mean()) / r.std()).round(2))
# [ 1.29 -0.77 -0.77 1.29 1.29 -0.77 -0.77 -0.77]
n, c, k = 10, 3, 5 # pass@k of section 4E
print(round(1 - comb(n - c, k) / comb(n, k), 3), round(1 - (1 - c / n) ** k, 3))
# 0.917 0.832
The fit puts the optimum at B parameters (45 tokens per parameter); the 20-tokens rule gives B. Inside a factor of 3 in , the loss changes by less than 1%. This flatness is why the exact ratio matters less than the inference cost.
6. Where it shows up #
- LLM work in industry. Every team that adapts an open model chooses SFT, DPO or RL by the data it has: demonstrations, preference pairs, or a checker. LoRA adapters let one server keep one base model and many small task adapters (lesson 13).
- Scientific foundation models. The same accounting sizes a weather or Earth-system model: a "token" is a patch of a field at one time step, and still counts the matrix FLOPs. The rule of 20 tokens per parameter was measured on web text; measure your own exponents with small runs before you spend the big budget. LoRA adapts a pretrained weather or protein model to a new region, variable or small assay data set, with a few MB per task.
- Rewards from physics. A simulator or a conservation check is a verifiable reward, so the ideas of section 3.8 carry over to generative models of physical fields. So does the risk: a field can conserve mass and still be wrong.
- Reading papers. Ask: is the gain larger than about 2 standard errors? Is the benchmark contaminated? Is perplexity compared across tokenizers?
7. Common mistakes #
- Treating 20 tokens per parameter as a law. It is the training-compute optimum of one fit on one data mix. Inference cost and data quality move the best choice.
- Forgetting what leaves out. Attention FLOPs at long context, recomputation, and the gap between peak and achieved FLOP/s (MFU).
- Comparing perplexities of models with different tokenizers. Use bits per byte.
- Computing the SFT loss on prompt tokens. The model then spends capacity on predicting user prompts. Mask them.
- Initializing both LoRA factors to zero (nothing trains) or both at random (the wrong starting model). Forgetting to freeze also removes all the memory savings.
- Saying "DPO has no reference model". It has one (frozen). SimPO and ORPO remove it.
- Saying "the reward went up, so the model is better". The reward model is a proxy. Watch the KL and a held-out gold evaluation.
- Using for pass@, and reporting differences smaller than their standard error.
8. Check yourself #
- How many H100 GPU-days does it take to train a 7 B model on 2 T tokens at 40% MFU?
Answer
FLOPs. One GPU gives FLOP/s, so GPU-seconds, about GPU-days (about 10 days on 256 GPUs). - Why is the KL penalty in RLHF needed, and what happens as ?
Answer
It keeps the policy near , where the reward model was trained and is reliable, and it keeps the text fluent. As the optimum puts all mass on the highest proxy reward: reward hacking. - In DPO, why does the partition function disappear?
Answer
The reward is . Bradley–Terry uses only the difference of the rewards of two responses to the same prompt, so cancels. - A GRPO group of 4 answers is all correct. What is the policy-gradient signal from it, and what can you do?
Answer
Zero: every , so all advantages are 0 (only the KL term acts). Filter such prompts and sample new ones (DAPO's dynamic sampling), or choose prompts of medium difficulty for the current model. - A projection gets LoRA with rank 16. How many trainable parameters, and what fraction of the matrix?
Answer
, which is . - When would you choose DPO over PPO, and when the other way round?
Answer
DPO: you have good preference pairs, limited compute, and want stability and simple code. PPO or GRPO: you need on-policy improvement beyond the data, you have a reliable reward model or a checker (math, code), and you can pay for generation in the loop.
About how many FLOPs does it take to train a dense transformer with parameters on tokens, and why that factor?
: per token for the forward pass and for the backward pass (input gradients and weight gradients).
What is the loss and the perplexity of a model that predicts uniformly over tokens?
Loss nats per token; perplexity .
What is the Chinchilla rule for a compute-optimal model?
About 20 training tokens per parameter, so and ; and grow by the same factor.
Why do labs train far past 20 tokens per parameter?
Chinchilla minimizes training compute only. Serving costs FLOPs per token for the life of the model, and the iso-FLOP curve is flat, so a smaller model trained longer is cheaper overall.
What is the optimal policy of ?
, with .
Write the DPO loss for one pair .
.
What is the GRPO advantage of answer in a group of answers?
, given to every token of answer . The group mean is the baseline; no value model.
How many trainable parameters does LoRA of rank add to a matrix?
, instead of for full fine-tuning.
Why does LoRA start with and random, and not both zero?
makes , so training starts at the pretrained model; keeps nonzero. With both zero, both gradients stay zero.
What does pass@ measure, and what is its unbiased estimator from samples with correct?
The chance that at least one of samples is correct; estimate it by .
9. Interview angle #
Recognize the question from the wording.
| The question says | Start with |
|---|---|
| "how is a chat model trained", "walk me through the pipeline" | the stage table of section 2; one equation and one number per stage |
| "how big a model for this budget", "how long will it train" | , , time |
| "Kaplan vs Chinchilla", "why does Llama train so long" | the schedule flaw; inference cost; the flat iso-FLOP curve |
| "derive DPO", "why no reward model" | the optimal-policy proof, then cancels |
| "we only have a unit-test checker", "reasoning" | RL with verifiable rewards, GRPO advantage, zero-signal groups |
| "fine-tune on one GPU", "many customers, one base model" | LoRA (and QLoRA): parameters, memory, merge |
| "is model B better?" | standard error, paired test, contamination, judge biases |
The routine to say aloud for any breadth question (60–90 seconds): give the one-sentence answer first; then one equation or one number; then one trade-off ("it costs …, it fails when …"); then stop and let the interviewer choose the follow-up.
Typical questions and short model answers.
- "Walk me through how a chat model is trained." — "Pretraining on about tokens with the next-token loss; that gives knowledge. Then mid-training on a cleaner mix while the learning rate decays. Then SFT on prompt–response pairs, with the loss only on response tokens; that gives the format. Then preference tuning, with a reward model and PPO or with DPO; that picks the answers people prefer. For math and code, RL with a checker, for example GRPO, which improves reasoning. Compute is about , so a 7 B model on 2 T tokens is about FLOPs."
- "Chinchilla vs Kaplan. Why does Llama train far past 20 tokens per parameter?" — "Chinchilla fitted and found that at fixed compute and should grow together, about 20 tokens per parameter. Kaplan used one schedule for all runs, so short runs looked worse than they were, and data was undervalued. Llama trains longer because Chinchilla counts only training compute. Inference costs per token forever, and the loss is flat near the optimum, so a smaller model trained longer is cheaper overall."
- "Derive DPO." — "Start from . Its solution is , because the objective equals plus a constant. Invert it: . Put this into Bradley–Terry; cancels because both answers share the prompt. Replace by and minimize the logistic loss on the pairs."
- "Why does GRPO need no value model? What can go wrong?" — "It samples a group of answers per prompt and uses the group mean as the baseline, normalized by the group std. That removes the value model and its memory. Problems: a group where all answers get the same reward gives zero signal; the std and length normalizations bias the update (Dr. GRPO removes them); and the checker can be gamed."
- "How do you know model B is better than model A?" — "Report the standard error: on 1,000 questions at 70% it is 1.4 points, so a 1.5-point gain is not significant. Use a paired test on the same questions, several seeds, and a check for contamination. If a model judges, swap the order and control for length."
- "LoRA or full fine-tuning?" — "LoRA trains parameters per matrix, so it saves the gradients and Adam states, gives small checkpoints, and lets one base serve many adapters; it also forgets less. It does not save activations. For a large domain shift, full fine-tuning has more capacity."
Typical follow-ups. "What does leave out?" (attention at long context, recomputation, MFU). "What happens if is too small?" (reward hacking; the KL grows). "Why does DPO lower the likelihood of both answers sometimes?" (it only needs the margin to grow). "What is pass@ and why not ?" (biased low, by Jensen). "Where do you put LoRA adapters?" (all linear layers when quality matters, as in QLoRA).
10. Practice #
The notebook for this lesson runs in Colab, in NumPy. Each exercise has a check cell and a folded solution:
chinchilla_optimum(C): the closed form of section 3.3, checked against a grid search on the iso-FLOP curve.kl_regularized_policy(pi_ref, r, beta): the optimal policy, checked to beat many random policies on the objective.dpo_lossand its gradient with respect to the two policy log-probabilities, checked by finite differences.grpo_advantages(rewards): the group-normalized advantages, with the zero-signal case.pass_at_k(n, c, k): the unbiased estimator, checked against a simulation.
The notebook also has a LoRA layer in NumPy: the output equals the base at the start, the gradients follow the theorem, and the merged weight gives the same output.
Timed practice (25 minutes each, talking aloud): derive on a blank page; derive the compute-optimal and ; derive and the DPO loss; implement a LoRA linear layer with merge and unmerge; implement the DPO loss for a batch of sequence log-probabilities.
Say it aloud drill. Start a 2-minute timer and answer "walk me through how a chat model is trained" aloud. Record yourself and compare with the stage table: did you give one equation and one number per stage? Then do the same for "derive DPO" in 3 minutes.
11. Watch and read #
- Stanford CS336 (Spring 2025), Lecture 9: Scaling laws 1 (video on YouTube; embedding is disabled): iso-FLOP curves and the Chinchilla analysis.
- Hoffmann et al. (2022), Training Compute-Optimal Large Language Models: §3 (the three methods) and the fit of approach 3.
- Besiroglu et al. (2024), Chinchilla Scaling: A replication attempt: the re-fit of the parametric loss.
- Kaplan et al. (2020), Scaling Laws for Neural Language Models: §2.1 (the FLOP count).
- Hu et al. (2021), LoRA: Low-Rank Adaptation of Large Language Models: §4 (the method and the initialization).
- Ouyang et al. (2022), Training language models to follow instructions with human feedback (InstructGPT): SFT, the reward model and PPO.
- Rafailov et al. (2023), Direct Preference Optimization: §4 and Appendix A.1 (the derivation of sections 3.6–3.7).
- Shao et al. (2024), DeepSeekMath: §4.1 (GRPO).
- Chen et al. (2021), Evaluating Large Language Models Trained on Code: §2.1 (pass@ and its unbiased estimator).
- Zheng et al. (2023), Judging LLM-as-a-Judge with MT-Bench and Chatbot Arena: the biases of model judges.
Runs in your browser with nothing to install. The notebook repeats the key demos and has exercises with checks; solutions are inside, folded.
No Google account needed: Python runs inside your browser. The first start downloads about 40 MB; your changes are saved in this browser only.