Pretraining vs SFT vs RLHF/DPO
Section focus: Explain every item aloud without notes
Description
Level 1 β The Simple Intuition (ELI5)
Think of training an LLM like educating a brilliant doctor:
- Pretraining is reading every book in the world's library for 10 years. The student absorbs vast knowledge of language, science, and code, but only knows how to continue textβif you ask
"What is the capital of France?", it might reply"What is the capital of Spain? What is the capital of Italy?"because it thinks it's reading a quiz worksheet!
- Supervised Fine-Tuning (SFT) is medical school residency with a mentor showing examples of "When a patient asks X, respond in a helpful, structured assistant format Y."
- RLHF / DPO (Alignment) is board certification feedback: the doctor writes two possible answers, and senior doctors grade "Response A is safer, clearer, and more honest than Response B."
Level 2 β How It Works (The 3-Stage Training Pipeline)
- Stage 1 β Self-Supervised Pretraining (Base Model):
- Data: Trillions of tokens () of filtered web text, books, papers, and code.
- Objective: Autoregressive Next-Token Prediction (Cross-Entropy Loss over all tokens):
- Result: High world knowledge ("entropy compression"), zero instruction-following format.
- Stage 2 β Supervised Fine-Tuning (SFT / Instruction Tuning):
- Data: high-quality
(prompt, response)pairs (written by human experts or distilled from stronger frontier models). - Objective: Same Cross-Entropy Loss, but masked to compute loss ONLY on the assistant response tokens (not the user prompt ):
- Result: Learns chat templates (
<|user|>,<|assistant|>), tone, and format ("Behavioral Cloning").
- Stage 3 β Preference Alignment (RLHF via PPO vs. DPO):
- Why SFT alone isn't enough: SFT forces the model to imitate every token of a reference answer, even when multiple valid phrasings exist, and cannot explicitly penalize subtle hallucinations, sycophancy, or unsafe completions that the base model assigns high probability to. It is much easier for humans to judge which of two answers is better () than to write the gold-standard answer from scratch.
Level 3 β Advanced Depth (RLHF/PPO vs. DPO vs. GRPO Math)
- RLHF with PPO (Proximal Policy Optimization):
- Collect preference triples where is preferred ("winner") over ("loser").
- Train a separate Reward Model using the Bradley-Terry pairwise loss:
- Optimize the policy online via RL (PPO) to maximize reward while staying close to the frozen SFT reference model via a KL-divergence penalty (which prevents "Reward Hacking", where the model outputs gibberish that tricks the reward model):
- Drawback of PPO: Requires loading 4 models in GPU memory simultaneously (Policy Actor , Reference , Reward , Critic/Value network ) and unstable online sampling.
- Direct Preference Optimization (DPO β Rafailov et al., 2023):
- Mathematically solves for the closed-form optimal policy of the KL-constrained reward maximization problem, substituting directly into the Bradley-Terry loss!
- Eliminates the separate Reward Model and online RL loop entirelyβoptimizing preference directly with a simple binary cross-entropy loss using only 2 models ( and frozen ):
- GRPO (Group Relative Policy Optimization β DeepSeekMath / DeepSeek-R1): Removes the Value/Critic network from PPO by sampling a group of outputs per prompt and normalizing their rewards relative to the group mean and standard deviation ()βideal for verifiable reasoning/coding rewards (RLVR).
Learning notes
End-to-End LLM Training Lifecycle
Loading diagramβ¦
Head-to-Head Comparison Across Training Stages
Dimension | Pretraining | Supervised Fine-Tuning (SFT) | RLHF (PPO) | DPO (Direct Preference Opt.) |
Primary Goal | Acquire world knowledge, grammar, reasoning primitives | Learn assistant format, tone, task structure | Maximize human/verifiable reward online | Directly increase margin between and offline |
Dataset Scale | raw tokens | curated instruction pairs | preference pairs + online rollouts | preference triples |
Loss Function | Unmasked Cross-Entropy | Prompt-Masked Cross-Entropy | Clipped Surrogate RL + KL Penalty | Implicit-Reward Bradley-Terry Log-Sigmoid |
Models in VRAM | () | () | (Actor, Critic, Reward, Ref) | (Policy , Frozen ) |
Training Stability | High (watch for loss spikes) | Very High | Low (sensitive to hyperparams & reward hacking) | High (standard supervised gradient descent) |
Example or implementation
PyTorch Implementation of the DPO Loss Function from Scratch
import torch import torch.nn.functional as F def compute_dpo_loss( policy_chosen_logps: torch.Tensor, # log pi_theta(y_w | x), shape: (B,) policy_rejected_logps: torch.Tensor, # log pi_theta(y_l | x), shape: (B,) ref_chosen_logps: torch.Tensor, # log pi_ref(y_w | x), shape: (B,) ref_rejected_logps: torch.Tensor, # log pi_ref(y_l | x), shape: (B,) beta: float = 0.1, ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """ Computes Direct Preference Optimization (DPO) loss and implicit rewards. """ # 1. Log-ratios between active policy and frozen SFT reference policy chosen_logratios = policy_chosen_logps - ref_chosen_logps rejected_logratios = policy_rejected_logps - ref_rejected_logps # 2. Implicit reward margin: beta * (log(pi/ref)_w - log(pi/ref)_l) logits = beta * (chosen_logratios - rejected_logratios) # 3. Binary cross-entropy loss: -log(sigmoid(logits)) losses = -F.logsigmoid(logits) # 4. Track implicit rewards for monitoring reward margin during training chosen_rewards = beta * chosen_logratios.detach() rejected_rewards = beta * rejected_logratios.detach() return losses.mean(), chosen_rewards.mean(), rejected_rewards.mean() # Quick verification loss, r_win, r_lose = compute_dpo_loss( policy_chosen_logps=torch.tensor([-12.0, -8.5]), policy_rejected_logps=torch.tensor([-15.0, -11.0]), ref_chosen_logps=torch.tensor([-13.0, -9.0]), ref_rejected_logps=torch.tensor([-14.0, -10.5]), beta=0.1, ) print(f"DPO Loss: {loss.item():.4f} | Implicit Reward (Win): {r_win.item():.3f} > (Lose): {r_lose.item():.3f}")
Interview-ready explanation
90-Second Spoken Pitch for Interviews
"Modern LLMs are trained in three stages that progressively shape raw knowledge into an aligned assistant.
First, Pretraining consumes trillions of web tokens using self-supervised next-token prediction. This builds the model's internal world model and reasoning circuits, which is why the Superficial Alignment Hypothesis notes that almost all knowledge is learned during pretraining. However, a base model only completes text documentsβit doesn't know how to act as an assistant.
Second, Supervised Fine-Tuning (SFT) trains on curated
(prompt, response) demonstrations, masking the cross-entropy loss so gradients only flow through the assistant's completion tokens. SFT teaches instruction following and formatting.Third, RLHF or DPO aligns the model with human preferences using comparison pairs . Classical RLHF with PPO trains a separate Bradley-Terry Reward Model and runs online reinforcement learning with a KL-divergence penalty against the frozen SFT reference model so the policy doesn't reward-hack. Direct Preference Optimization (DPO) algebraically reparameterizes the reward function in terms of the policy-to-reference log-probability ratio , allowing us to optimize preferences directly with a stable cross-entropy loss and only two models in memory instead of four."