Skip to main content

Large Language Models

From GPT to ChatGPT and beyond: scaling laws and compute-optimal training, instruction tuning and supervised fine-tuning, reward models and RLHF with the KL-regularized optimal policy and DPO, hallucination, retrieval and reasoning models trained with verifiable rewards, speculative decoding, and multimodal models from Flamingo and LLaVA to unified models.

A base GPT (Ch. 9) is pretrained to continue text. A chat assistant is trained further to respond: follow instructions, prefer helpful and honest answers, and admit what it does not know. The modern pipeline is

\[ \text{pretraining}\;\to\;\text{base model}\;\to\;\text{supervised fine-tuning}\;\to\;\text{preference optimization}\;\to\;\text{assistant}. \]

The guiding slogan: capability comes from pretraining; behavior comes from post-training. This chapter follows that pipeline, then turns to reasoning models, faster decoding, and multimodal models.

10.1 Scaling Laws

From GPT-1 to GPT-3 the recipe barely changed; the scale did. Kaplan et al. (2020) measured how the test loss of autoregressive transformer language models depends on scale.

Definition 10.1 (Neural Scaling Laws) When the other two factors are not the bottleneck, the test cross-entropy loss follows a power law in each of the number of non-embedding parameters \(N\), the number of training tokens \(D\), and the training compute \(C\):

\[ L(N)\approx\Bigl(\frac{N_c}N\Bigr)^{\alpha_N}, \qquad L(D)\approx\Bigl(\frac{D_c}D\Bigr)^{\alpha_D}, \qquad L(C)\approx\Bigl(\frac{C_c}C\Bigr)^{\alpha_C}, \]

with small exponents (Kaplan et al. measured \(\alpha_N\approx0.076\), \(\alpha_D\approx0.095\), \(\alpha_C\approx0.05\)). Training costs about \(C\approx6ND\) floating-point operations.

  • Scale dominates, shape barely matters. At a fixed parameter count, depth versus width, the number of attention heads, and the FFN ratio change the loss only slightly.
  • Bigger models are more sample-efficient: they reach a given loss with fewer tokens and fewer optimization steps. To avoid overfitting, data should grow sublinearly with model size, roughly \(D\propto N^{0.74}\).
  • Compute-optimal training. For a fixed budget \(C\), Kaplan et al. found that most extra compute should go into a larger model (\(N\propto C^{0.73}\)) rather than many more serial steps. Later work (Chinchilla, Hoffmann et al., 2022) revised this to scaling \(N\) and \(D\) about equally, roughly 20 tokens per parameter.
  • So, to improve a language model, scale parameters, data, and compute together. Loss falls predictably along a smooth curve, which is what made it rational to train very large models.

Each token costs about \(2N\) FLOPs in the forward pass (one multiply and one add per parameter) and about \(4N\) in the backward pass, which gives \(C\approx6ND\).

A \(7\times10^9\)-parameter model trained on \(2\times10^{12}\) tokens needs \(C\approx6\times7\times10^9\times2\times10^{12}=8.4\times10^{22}\) FLOPs. At a sustained \(4\times10^{14}\) FLOP/s per accelerator, that is about \(2.1\times10^8\) accelerator-seconds: roughly \(1000\) accelerators for \(2.4\) days. The Chinchilla rule would call \(20\times7\times10^9=1.4\times10^{11}\) tokens compute-optimal for this size; training far beyond that is common when the model will serve many users, because a smaller, longer-trained model is cheaper at inference time.

10.2 Instruction Tuning

Pretraining is not instruction following. Pretraining sees plain text \(x_1,\dots,x_T\) and learns to continue it. Asked “Explain the moon landing to a six-year-old”, early GPT-3 might continue with more similar questions instead of answering.

Definition 10.2 (Supervised Fine-Tuning) Supervised fine-tuning (SFT), or instruction tuning, trains a pretrained model on instruction–response pairs \((x,y)\) by maximum likelihood on the response tokens:

\[ \max_\theta\;\mathbb E_{(x,y)}\sum_t\log\pi_\theta\bigl(y_t\mid x,y_{<t}\bigr). \]

FLAN (Wei et al., 2021) instruction-tuned a 137B pretrained model on 62 datasets in 12 task clusters, each phrased with 10 hand-written instruction templates.

  • Zero-shot FLAN beat zero-shot GPT-3 (175B) on 20 of 25 held-out datasets, and even few-shot GPT-3 on several.
  • Multitask fine-tuning without the instructions helped much less: the natural-language phrasing is crucial.
  • More task diversity helps on unseen tasks; the benefit appears only at large scale (it can hurt small models); and it helps most on tasks naturally phrased as instructions.

Why SFT alone is not enough.

  • Many prompts have many acceptable answers, but SFT imitates one reference answer and learns no ranking between answers.
  • It does not directly optimize clarity, concision, helpfulness, honesty, or harmlessness, i.e. whether answer A is better than answer B.
  • It learns only from positive examples.

10.3 Learning from Human Preferences

Reinforcement learning frames sequential decision making: an agent observes the environment, takes actions, and receives rewards; the policy is trained by trial and error to maximize expected reward, learning from both good and bad outcomes of its own exploration. A language model fits this frame: the prompt is the observation, each generated token is an action, and the reward judges the finished response. The missing piece is the reward: instructions are complex and diverse, and judging a response is hard to automate.

InstructGPT (OpenAI, 2022) supplies it with human feedback in three steps:

  1. SFT on human-written demonstrations;
  2. sample several responses per prompt, have humans rank them, and fit a reward model to the rankings;
  3. optimize the SFT model with RL against the learned reward (RLHF).

Definition 10.3 (Reward Model and RLHF Objective) A reward model \(r_\phi(x,y)\) is fitted to pairwise human preferences \(y^+\succ y^-\) with the Bradley–Terry model:

\[ P(y^+\succ y^-\mid x)=\sigma\bigl(r_\phi(x,y^+)-r_\phi(x,y^-)\bigr), \qquad L(\phi)=-\mathbb E\log\sigma\bigl(r_\phi(x,y^+)-r_\phi(x,y^-)\bigr). \]

RLHF then maximizes reward while staying close to a reference model \(\pi_{\text{ref}}\) (the SFT model):

\[ \max_\pi\;\mathbb E_{x,\,y\sim\pi(\cdot\mid x)}\bigl[r_\phi(x,y)\bigr]-\beta\,\mathrm{KL}\bigl(\pi(\cdot\mid x)\,\big\|\,\pi_{\text{ref}}(\cdot\mid x)\bigr). \]

  • A ranking of \(K\) responses gives \(\binom K2\) comparison pairs.
  • The KL penalty keeps the policy from drifting into regions where the learned reward is unreliable, which would let it hack the reward with degenerate text. In InstructGPT the objective is optimized with PPO.

Theorem 10.1 (Optimal KL-Regularized Policy) For each prompt \(x\), the RLHF objective is maximized by

\[ \pi^\star(y\mid x)=\frac1{Z(x)}\,\pi_{\text{ref}}(y\mid x)\exp\Bigl(\frac{r(x,y)}\beta\Bigr), \qquad Z(x)=\sum_y\pi_{\text{ref}}(y\mid x)\exp\Bigl(\frac{r(x,y)}\beta\Bigr). \]

Fix \(x\) and write \(\pi=\pi(\cdot\mid x)\). Since \(r=\beta\log\frac{\pi^\star Z}{\pi_{\text{ref}}}\),

\[ \mathbb E_\pi[r]-\beta\,\mathbb E_\pi\Bigl[\log\frac{\pi}{\pi_{\text{ref}}}\Bigr] =\beta\,\mathbb E_\pi\Bigl[\log\frac{\pi^\star Z}{\pi_{\text{ref}}}-\log\frac{\pi}{\pi_{\text{ref}}}\Bigr] =-\beta\,\mathrm{KL}(\pi\|\pi^\star)+\beta\log Z(x). \]

\(Z\) does not depend on \(\pi\), and the KL is minimized, with value \(0\), exactly at \(\pi=\pi^\star\).

  • The optimal policy reweights the reference model by \(e^{r/\beta}\): small \(\beta\) trusts the reward, large \(\beta\) stays near \(\pi_{\text{ref}}\).

Proposition 10.1 (Direct Preference Optimization) Inverting Theorem 10.1 gives \(r(x,y)=\beta\log\frac{\pi^\star(y|x)}{\pi_{\text{ref}}(y|x)}+\beta\log Z(x)\). Substituting into the Bradley–Terry loss, \(Z(x)\) cancels in the difference, which gives a loss on the policy itself:

\[ L_{\text{DPO}}(\theta)=-\mathbb E_{(x,y^+,y^-)}\log\sigma\Bigl(\beta\log\frac{\pi_\theta(y^+\mid x)}{\pi_{\text{ref}}(y^+\mid x)}-\beta\log\frac{\pi_\theta(y^-\mid x)}{\pi_{\text{ref}}(y^-\mid x)}\Bigr). \]

  • DPO (Rafailov et al., 2023) fits the preferences directly with a classification-style loss: no separate reward model, no sampling, no RL loop. It trades RL’s online exploration for simplicity and stability.
pretraining post-training (alignment)
data massive corpus small, high-quality
objective compression (next token) instruction following, human preference
dynamics static dataset online feedback

10.3.1 Why RLHF Helps: Hallucination

A thought experiment (Schulman, 2023): suppose a model’s knowledge ends in 2023, and SFT teaches it to describe Euro 2024. The model does not know the facts, so SFT teaches it to produce confident answers it cannot back up: to hallucinate. SFT uses only positive examples; it cannot say “this answer is bad”. RL can, through rewards that penalize wrong answers and reward honest uncertainty.

Asked “Who won the 2026 World Cup?” beyond its knowledge, a pretrained model spreads its answers as \(P(\text{Spain})=0.3\), \(P(\text{Argentina})=0.3\), \(P(\text{I don't know})=0.4\). Any specific answer is a guess, so let the reward be \(-4\) for each team and \(+0.5\) for “I don’t know”. By Theorem 10.1 with \(\beta=1\), the RLHF optimum reweights by \(e^{r}\):

\[ \pi^\star\propto\bigl(0.3e^{-4},\;0.3e^{-4},\;0.4e^{0.5}\bigr)\approx(0.0055,\;0.0055,\;0.659), \]

which normalizes to \(P(\text{I don't know})\approx0.98\). With \(\beta=2\) the policy stays closer to the reference: \(\approx0.86\). The reward model must be designed well: if it rewarded confident-sounding answers, RL would amplify hallucination instead.

  • RL also lets the model explore its own outputs and learn from negative samples, which can raise capability, not only fix behavior.

10.4 Beyond the Weights: Retrieval and Reasoning

New facts will always appear after the training cutoff.

  • Retrieval-augmented generation (RAG): before answering, retrieve relevant documents and put them in the context. Knowledge is updated by updating the index, with no retraining.

Some questions need reasoning rather than recall: “make 24 from 4, 4, 7, 7” requires trying and checking combinations, as a person would.

  • Chain-of-thought prompting (2022): prompts that elicit intermediate steps before the answer improve accuracy on multi-step problems, much as more in-context examples improved GPT-3.
  • Reasoning models (OpenAI o1, 2024, and successors) generate long hidden thinking tokens before the visible answer. They exhibit inference-time scaling: thinking longer gives better answers.

Definition 10.4 (Reinforcement Learning with Verifiable Rewards) Train a reasoning model by RL on prompts whose answers can be checked automatically (math, code, logic puzzles):

  • action: the thinking tokens and the final answer, generated by the model’s own exploration;
  • reward: from a verifier comparing the answer with the ground truth, e.g. \(+1\) if correct and \(-1\) otherwise.

No “correct” thinking tokens are ever supervised; only the outcome is rewarded.

  • Since the space of possible thoughts is enormous, the reward must be accurate: a verifier, not a learned judge, is what makes this stable. For the 24 puzzle, the verifier evaluates \((4-4/7)\times7=24\) and returns \(+1\), but \((4+4)\times(7+7)=112\) earns \(-1\).
  • RL becomes a new axis of scaling: longer RL training gives stronger reasoning, and the responses grow longer as training proceeds.
  • From reasoning to acting. An LLM that calls tools and interacts with an environment is an LLM agent (deep research, general assistants), and it can be trained with RL in the same way (Ch. 14).

10.5 Speculative Decoding

Generating each token requires a full forward pass of the large model, and that pass is limited by memory bandwidth, not arithmetic. Speculative decoding (Leviathan et al., 2023) lets a small, fast draft model \(q\) propose \(k\) tokens, which the large target model \(p\) then checks all at once in a single parallel forward pass.

Theorem 10.2 (Speculative Sampling Is Exact) At each position, given the same prefix, draw a candidate \(y\sim q\) and

  • accept it with probability \(\min\bigl(1,p(y)/q(y)\bigr)\);
  • if rejected, draw a replacement from the residual distribution \(r(y)=\dfrac{[p(y)-q(y)]_+}{\sum_v[p(v)-q(v)]_+}\), and discard the remaining draft tokens.

Then each emitted token is distributed exactly as \(p(\cdot\mid\text{prefix})\), and the generated sequence follows \(p(y_{1:k}\mid x)\).

One token. The probability of emitting \(y\) by acceptance is \(q(y)\min\bigl(1,\frac{p(y)}{q(y)}\bigr)=\min\bigl(p(y),q(y)\bigr)\). The total rejection probability is

\[ 1-\sum_v\min(p(v),q(v))=\sum_v\bigl(p(v)-\min(p(v),q(v))\bigr)=\sum_v[p(v)-q(v)]_+, \]

which is exactly the normalizer of \(r\). So the probability of emitting \(y\) is

\[ \min(p(y),q(y))+\sum_v[p(v)-q(v)]_+\cdot\frac{[p(y)-q(y)]_+}{\sum_v[p(v)-q(v)]_+}=\min(p(y),q(y))+[p(y)-q(y)]_+=p(y). \]

A sequence. Apply the argument at each position, conditioned on the prefix emitted so far; once a token is rejected and resampled, the later draft tokens are discarded and drafting restarts from the new prefix. By the chain rule, \(\pi(y_{1:k}\mid x)=\prod_ip(y_i\mid x,y_{<i})=p(y_{1:k}\mid x)\).

  • Speculative decoding changes the speed, never the output distribution. If all \(k\) drafts are accepted, the target’s pass also provides one extra token for free.
  • The per-token acceptance probability is \(\alpha=\sum_y\min(p,q)=1-\mathrm{TV}(p,q)\). If acceptances were independent, each target pass would yield on average \((1-\alpha^{k+1})/(1-\alpha)\) tokens: about \(3.4\) for \(\alpha=0.8\) and \(k=4\).

10.6 Multimodal Models

Language-only models know facts about the world but cannot see images, charts, or interfaces. Multimodal models combine language with perception.

  • Flamingo (DeepMind, 2022) asks whether GPT-style in-context learning works with images and video. It connects a frozen vision encoder and a frozen language model with two new parts: a Perceiver Resampler, which compresses many visual features into a few visual tokens, and gated cross-attention layers inserted into the language model (with gates initialized to zero, so training starts from the unchanged LM). It takes text interleaved with images and outputs text; with 32 examples in the prompt it beat fine-tuned state of the art on 6 of 16 benchmarks, improving with model size and number of shots.
  • LLaVA (2023) targets instruction following rather than few-shot prompting. A CLIP vision encoder feeds an LLM (Vicuna) through a simple linear projection into the LLM’s embedding space. Training has two stages: feature alignment (train only the projection) and visual instruction tuning (freeze the vision encoder, train the projection and the LLM) on instruction data generated with GPT-4. On LLaVA-Bench (COCO), instruction tuning raised the score from 21.5 to 85.1 (relative to a GPT-4 reference).
  • Unified models (e.g. BAGEL, 2025) do understanding, generation, and editing in one decoder-only model: two transformer experts (understanding and generation) share multimodal self-attention, with a ViT encoder for understanding and a VAE latent (Ch. 6) for generation, pretrained on interleaved text, image, and video data. Skills emerge in order with scale: understanding first, then generation, then editing, and reasoning-based editing last.

10.7 Supplementary Notes

10.7.1 Key Results

  • Definition 10.1: \(L\propto N^{-\alpha_N},D^{-\alpha_D},C^{-\alpha_C}\); \(C\approx6ND\); Chinchilla \(\approx20\) tokens per parameter.
  • Definition 10.2: SFT maximizes \(\sum_t\log\pi_\theta(y_t\mid x,y_{<t})\).
  • Definition 10.3: Bradley–Terry \(P(y^+\succ y^-)=\sigma(r^+-r^-)\); RLHF \(\max\mathbb E[r]-\beta\mathrm{KL}(\pi\|\pi_{\text{ref}})\).
  • Theorem 10.1: \(\pi^\star\propto\pi_{\text{ref}}e^{r/\beta}\).
  • Proposition 10.1: DPO loss \(-\log\sigma\bigl(\beta\log\frac{\pi_\theta(y^+)}{\pi_{\text{ref}}(y^+)}-\beta\log\frac{\pi_\theta(y^-)}{\pi_{\text{ref}}(y^-)}\bigr)\).
  • Definition 10.4: RL with verifier rewards trains reasoning without supervising thoughts.
  • Theorem 10.2: accept with \(\min(1,p/q)\), resample from \([p-q]_+\); output is exactly \(p\).