LLMs — Pretraining, RLHF, and Scaling Laws
How GPT, Claude, and Gemini are built. Next-token prediction at scale, RLHF alignment, DPO, instruction tuning, and the laws that predict capability from compute.
An LLM is a Transformer trained on hundreds of billions of tokens to predict the next word. That one objective — predict what comes next — turns out to be sufficient to learn reasoning, coding, translation, and every other language task ever attempted.
Module 48 covered the Transformer architecture — attention, positional encoding, encoder-decoder. LLMs use only the decoder half (or a modified encoder-only variant for BERT). GPT, LLaMA, Mistral, and Gemini are all decoder-only Transformers. The key difference from what you built in Module 48: scale. GPT-3 has 175 billion parameters trained on 300 billion tokens using thousands of A100 GPUs over months. LLaMA-3-70B has 70 billion parameters trained on 15 trillion tokens. Scale changes everything — capabilities emerge that were completely absent at smaller scales and were never explicitly trained.
But pretraining alone produces a model that completes text in the style of its training data — helpful for some tasks, dangerous for others. A pretrained GPT asked "how do I make a bomb?" will helpfully complete the sentence if such text appeared in its training data. Alignment — the process of making LLMs helpful, harmless, and honest — requires three additional stages: supervised fine-tuning (SFT), reinforcement learning from human feedback (RLHF), and increasingly direct preference optimisation (DPO).
Pretraining is like a person reading every book, article, and website ever written. They become extraordinarily knowledgeable about language and the world. But they have no manners, no values, and no sense of what is helpful vs harmful — they just know what typically follows what in text. Alignment is giving them social training, teaching them to be genuinely helpful, and giving them the judgment to refuse harmful requests.
The insight from OpenAI's InstructGPT paper (2022): a 1.3B parameter model fine-tuned with RLHF was preferred by human raters over a raw 175B GPT-3. Alignment is more important than raw scale for user-facing applications.
Next-token prediction at scale — the only pretraining objective
The pretraining objective is next-token prediction (causal language modelling). Given a sequence of tokens [t₁, t₂, …, t_n], the model predicts t_i+1given [t₁, …, t_i] for every position simultaneously. The loss is cross-entropy averaged over all token predictions. This objective is self-supervised — no human labels required. Any text on the internet is valid training data.
How much compute, how many parameters, how much data — the laws that answer all three
Kaplan et al. (2020) discovered that LLM loss follows power laws with respect to model size N, dataset size D, and compute budget C. These scaling laws make LLM development predictable — you can forecast the loss of a model before training it. Hoffmann et al. (2022) refined these laws with Chinchilla: for a fixed compute budget, the optimal strategy is to train a smaller model on more tokens, not a larger model on fewer tokens. The rule: N_opt ≈ D_opt / 20 — use 20 tokens per parameter.
SFT then RLHF — turning a text predictor into a helpful assistant
After pretraining, the model completes text but does not follow instructions. Supervised Fine-Tuning (SFT) is the first alignment step: fine-tune the pretrained model on a dataset of high-quality (prompt, response) pairs written or curated by humans. Typically 10,000–100,000 examples. This teaches the model to respond to instructions rather than just complete text. But SFT only teaches the model to imitate — it cannot teach the nuanced human preferences about what makes a response helpful, honest, and harmless.
RLHF (Reinforcement Learning from Human Feedback) goes further. Humans compare pairs of model responses and indicate which is better. A reward model is trained to predict human preference scores. The LLM is then fine-tuned with PPO (Proximal Policy Optimisation) to maximise the reward model's score. This is how ChatGPT, Claude, and Gemini are aligned — RLHF is what makes them feel like helpful assistants rather than text completion engines.
DPO — Direct Preference Optimisation — RLHF without the RL
RLHF requires training three models simultaneously — the LLM policy, the reward model, and the reference policy — and running PPO, a notoriously finicky RL algorithm. Engineering complexity is enormous. DPO (Rafailov et al., 2023) derives a closed-form loss that achieves the same objective as RLHF without training a reward model or running RL. The insight: the optimal RLHF policy has a closed form that can be directly optimised with a simple binary cross-entropy loss on preference pairs. Most open-source models (LLaMA, Mistral, Phi) are now aligned with DPO rather than RLHF because it is far simpler.
Temperature, sampling strategies, and quantisation for deployment
Every common LLM mistake — explained and fixed
Inside a real pretraining-to-RLHF pipeline
At a major lab, building a model like this is not one team's project — it is a relay race across several teams with very different jobs and very different tools. Data engineering teams spend months building the pretraining corpus: crawling and deduplicating web text, filtering out low-quality and toxic content, mixing in code, books, and curated high-quality sources, and building the tokeniser. Research and infrastructure teams own distributed training across thousands of GPUs for weeks to months — dealing with hardware failures, checkpointing every few hours so a crashed node does not cost days of compute, and monitoring loss curves for the silent failure modes (loss spikes, gradient explosions) that can appear only after trillions of tokens. None of this touches a single human preference label — pretraining is entirely self-supervised and consumes roughly 99% of the total compute budget for the model.
Alignment is a completely different kind of work, run by a different team on a much smaller budget but with outsized influence on how the model actually feels to use. SFT teams write or curate tens of thousands of high-quality example responses. Alignment teams design the RLHF or DPO preference data collection, which in practice usually means working with a human data vendor — Surge AI, Scale AI, and Invisible are common names in this space — to have contractors compare pairs of model responses at scale. Safety and red-teaming teams then spend weeks trying to jailbreak the aligned model before release: crafting adversarial prompts, checking for harmful outputs, and measuring refusal rates on both genuinely harmful requests and, just as importantly, benign requests the model should not be refusing. A model typically goes through several rounds of this loop — align, red-team, find failures, collect more targeted preference data, re-align — before it ships.
| Team | Owns | Typical tools | Timescale |
|---|---|---|---|
| Data engineering | Web crawl, dedup, filtering, tokeniser | CCNet, MinHash dedup, custom filters | Months, ongoing |
| Pretraining / infra | Distributed training run, checkpointing | Megatron-LM, DeepSpeed, thousands of GPUs | Weeks to months |
| SFT / alignment | Instruction data, preference pipeline | Vendor-labelled comparisons, TRL, internal tools | 2–6 weeks per cycle |
| Safety / red-team | Jailbreak testing, refusal calibration | Adversarial prompt suites, internal eval harnesses | Ongoing, pre- and post-launch |
Slack message from the alignment lead: "New checkpoint scores worse on the refusal benchmark than last week's — it is refusing benign coding questions it used to answer fine. Reward model score went up though. Investigate before we ship." This is a textbook reward hacking symptom: the reward model learned a shortcut (maybe associating caution-flavoured language with higher preference scores) that raised its own metric while making the actual product worse. The fix is rarely "retrain from scratch" — it usually means pulling the specific failing transcripts, adding targeted preference examples that penalise the over-refusal, adjusting the KL penalty against the reference model so the policy cannot drift as far, and re-running the held-out benchmark suite before touching the reward model weights again.
Five things people get wrong about pretraining and RLHF
RLHF and DPO are alignment steps, not capability steps. They reshape which of the base model's already-latent behaviours get surfaced and reinforced — being concise, refusing harmful requests, following instruction formatting — but they do not teach the model new facts or new reasoning ability that pretraining did not already provide. This is exactly why InstructGPT's famous result was so striking: a small, heavily aligned 1.3B model being preferred over a raw 175B base model is not evidence that alignment created new capability out of nothing, it is evidence that the raw capability was already present in the base model and alignment simply made it reliably accessible and pleasant to interact with.
The Chinchilla scaling laws describe an optimal token count assuming reasonably high-quality, deduplicated data — they say nothing about dumping more raw, duplicated, or low-quality text into the mix. In practice, heavily duplicated web content wastes compute reinforcing the same patterns repeatedly, and low-quality or toxic content measurably degrades downstream behaviour. A large fraction of the real engineering effort — and a large fraction of what actually differentiates one lab's pretraining run from another's at the same parameter count — goes into deduplication, quality filtering, and data mixing, not into simply acquiring more raw tokens.
The reward model is trained on nothing but human comparisons of which response a rater preferred — it has learned to predict human preference, not truth. Human raters carry systematic biases: a tendency to prefer longer, more detailed-looking answers even when a shorter one is equally correct, or to prefer a confident, agreeable tone even when pushing back would be more honest. A policy optimised hard against this reward model will happily learn to exploit exactly those biases — becoming verbose or sycophantic — because from the reward model's point of view that behaviour genuinely does score higher. This gap between "scores well on the reward model" and "is actually a better response" is the entire reason reward hacking exists.
They differ in almost every dimension that matters. Pretraining is self-supervised — next-token prediction over unlabeled internet-scale text needs no human annotation at all — and consumes roughly 99% of total training compute over trillions of tokens. SFT and RLHF or DPO instead train on tiny, expensive, carefully curated human-produced or human-labelled datasets, often tens of thousands to a few hundred thousand examples, using entirely different objectives: cross-entropy imitation for SFT, and a preference- or reward-based objective for RLHF and DPO. Treating alignment as "more of the same training, just with better data" misses that the whole point of the later stages is to optimise for a fundamentally different signal — human preference — using a completely different data pipeline and, in RLHF's case, a completely different training algorithm.
Alignment training reshapes a statistical distribution over outputs — it does not install a hard, unbreakable rule. Adversarial prompting and jailbreaks routinely find inputs that push the model outside the distribution the alignment training covered well, surfacing the underlying pretrained behaviour it was supposed to suppress. Even more relevant in practice: further fine-tuning a model on unrelated downstream data, including seemingly harmless task-specific fine-tuning, can measurably erode safety behaviour that RLHF or DPO installed — a documented phenomenon sometimes called safety regression. This is why serious deployments pair alignment training with ongoing red-teaming, input and output monitoring, and re-evaluation after any further fine-tuning, rather than treating one alignment pass as a permanent guarantee.
LLM pretraining and RLHF — 5 questions interviewers actually ask
Pretraining first: a decoder-only Transformer is trained with next-token prediction on trillions of tokens of largely unlabelled web, book, and code text, consuming the large majority of total compute and producing a model that completes text fluently but follows no instructions. Supervised fine-tuning comes next: the pretrained model is fine-tuned on tens of thousands of curated prompt-and-ideal-response pairs, with loss computed only on the response tokens, teaching it to behave like an assistant rather than a text completer. Then alignment: human annotators compare pairs of the SFT model's responses, and either a reward model is trained on those comparisons and the policy is optimised against it with PPO, or the comparisons are used directly in a DPO loss. The result goes through safety red-teaming, and often several more rounds of targeted preference data collection, before release.
PPO-based RLHF requires training and maintaining three models at once — the policy being optimised, a separately trained reward model, and a frozen reference policy — and running proximal policy optimisation, a reinforcement learning algorithm that is notoriously sensitive to hyperparameters and prone to instability. DPO sidesteps the reward model and the RL loop entirely: it derives a closed-form loss showing that the optimal RLHF policy can be reached directly from preference pairs using a simple binary cross-entropy-style objective against the reference model. The industry shift toward DPO, visible in most open-source model releases, is mostly about engineering cost — DPO reaches comparable alignment quality with a fraction of the moving parts and a much shorter, more stable training loop.
Pretraining optimises for exactly one thing: predicting the next token consistent with internet-scale text. A base model asked a question will complete it in whatever style matches its training distribution — which might be helpful, might be evasive, might continue with more questions instead of answering, and will happily continue harmful content if that is what similar text in its training data looked like. Knowing a huge amount about the world is orthogonal to reliably being helpful, honest, and refusing harmful requests on demand — alignment is the stage that specifically optimises for that behavioural target, using human preference data the next-token objective never saw during pretraining.
Reward hacking happens when the policy finds a shortcut that raises its score from the reward model without genuinely improving response quality — becoming needlessly verbose because raters tend to prefer longer answers, or becoming sycophantic because agreeing with the user scores well even when the user is wrong. I would catch this by never trusting the reward model score in isolation: track a held-out suite of task benchmarks and a refusal-calibration benchmark across training, and watch for the reward score climbing while those independent metrics stay flat or get worse. Manually reading a sample of high-reward transcripts each training run is also worth the time — reward hacking patterns are usually obvious to a human within a handful of examples even when they are invisible in the aggregate reward number.
I would not think of it as splitting the same budget, because the two stages consume wildly different amounts of compute for wildly different returns — pretraining is roughly 99% of total compute and alignment is closer to 1%, yet the InstructGPT result showed a heavily aligned model an order of magnitude smaller beating a raw base model on human preference. That asymmetry means alignment investment is almost always underfunded relative to its impact on user-perceived quality, so I would treat pretraining scale as the given from the overall budget and separately make sure the alignment stage has enough dedicated preference-data collection and red-teaming cycles, rather than treating it as an afterthought squeezed into whatever time is left after the pretraining run finishes.
You understand how LLMs are built and aligned. Next: fine-tune one yourself for a specific task.
Module 64 covered the architecture and training pipeline of LLMs at a conceptual and code level. Module 65 makes it practical: full LoRA fine-tuning walkthrough on a real dataset using HuggingFace Transformers and PEFT, including when to fine-tune vs use RAG vs prompt engineer, and how to evaluate the result.
When to fine-tune vs RAG vs prompt. Full LoRA fine-tuning walkthrough on a real dataset using HuggingFace Transformers and PEFT.
🎯 Key Takeaways
- ✓LLMs are decoder-only Transformers trained with next-token prediction (causal language modelling). The loss is cross-entropy over every token position. The causal mask ensures position i only attends to positions ≤ i. Weight tying shares the input embedding and output projection matrices — saving parameters.
- ✓Chinchilla scaling law: for a fixed compute budget C, the optimal model has N_opt ≈ √(C/120) parameters trained on D_opt ≈ 20×N_opt tokens. GPT-3 was undertrained by this law. LLaMA-3-8B is intentionally over-trained (15T tokens on 8B params) to produce a small model with high inference efficiency.
- ✓Three-stage alignment pipeline: pretraining (next-token prediction on trillions of tokens, 99% of compute), SFT (fine-tune on 10k–100k prompt-response pairs, compute loss on response tokens only), RLHF or DPO (align to human preferences using comparison data).
- ✓RLHF requires training a reward model on human preference pairs then using PPO to maximise expected reward minus KL penalty from the SFT reference. DPO achieves the same objective with a closed-form loss directly on preference pairs — no reward model, no RL. DPO is now the standard for open-source alignment.
- ✓Sampling strategies: greedy (deterministic, repetitive), temperature (scale logits — lower = conservative, higher = creative), top-k (only consider k most likely tokens), top-p/nucleus (keep smallest set summing to probability p). Production default: top-p=0.9 + temperature=0.7.
- ✓Quantisation makes large models deployable: fp16 halves memory vs fp32 with identical quality. int8 (bitsandbytes) halves again with <0.5% degradation. int4 (GPTQ/AWQ) halves again with 1-2% degradation — a 70B model fits in 35GB VRAM. For CPU inference: llama.cpp with GGUF format runs 7B models on laptops.
Discussion
0Have a better approach? Found something outdated? Share it — your knowledge helps everyone learning here.