Fine-Tuning, RLHF & Prompting
Turning a text predictor into a helpful assistant.
Ask a freshly pretrained language model "How do I boil an egg?" and it may answer, or it may continue with three more questions, as if copying a forum page. Turning that text predictor into an assistant takes surprisingly little: thousands of demonstrations, cheap low-rank weight updates, a reward learned from people's comparisons, and a well-chosen leash. This lesson derives each piece.
What you’ll learn
- Write the supervised fine-tuning objective, and derive the parameter and memory savings of low-rank adaptation (LoRA).
- Fit a Bradley–Terry reward model to pairwise preferences and compute its gradient.
- Derive the optimum of the KL-regularized RLHF objective, , and from it the DPO loss.
- Explain how prompting and retrieval supply knowledge at inference time, and why evaluating assistants is hard.
From predictor to instruction follower
A pretrained language model defines a distribution over continuations of a prompt (see Large Language Models: Pretraining & Scaling). From here on, call it a policy: post-training changes which continuations it prefers.
The recipe popularized by InstructGPT (Ouyang et al., 2022) has three stages: supervised fine-tuning (SFT) on demonstrations written by people, a reward model trained on their comparisons of model outputs, and reinforcement learning against that reward, the RLHF step. The first stage is ordinary maximum likelihood:
Does such training teach the format of particular tasks, or the general skill of following instructions? Instruction tuning tested this. FLAN (Wei et al., 2022) fine-tuned a 137-billion-parameter pretrained model on more than 60 NLP datasets rewritten as natural-language instructions, then evaluated it on whole task types held out from training. Zero-shot performance on the unseen types rose for the largest models, while for models of 8 billion parameters and fewer instruction tuning hurt it.
Behavior is cheaper to change than capability: InstructGPT's labelers preferred the outputs of a 1.3-billion-parameter InstructGPT model to those of the 175-billion-parameter GPT-3.
| Stage | Data | Objective | What it changes |
|---|---|---|---|
| SFT | prompts with responses written by people | likelihood of the response | format, style, basic instruction following |
| Reward modeling | prompts, several responses, human rankings | Bradley–Terry likelihood of the rankings | nothing in the policy yet: a scalar score of response quality |
| RL (PPO) | prompts only; responses sampled from the policy | expected reward minus a KL penalty | shifts probability toward high-reward responses |
Think first Why not skip SFT and run reinforcement learning against the reward model directly from the pretrained model?
RL samples responses from the current policy and can only reweight what it samples. A pretrained model rarely produces a well-formed assistant answer, so early rewards are uninformative and training is slow and unstable; worse, the reward model was trained on SFT-style outputs and is unreliable far from them. SFT moves the starting distribution to where the reward is meaningful. (RL from a base model can work when rewards are verifiable, such as checked math answers; see Neurosymbolic AI & Reasoning Models.)
Parameter-efficient fine-tuning: LoRA
Full fine-tuning updates every weight. With mixed-precision Adam that costs about 16 bytes per parameter: 16-bit weights and gradients, plus 32-bit master weights and two moment estimates (Rajbhandari et al., 2020). A 7-billion-parameter model needs about 112 GB before a single activation is stored, and every task gets its own full copy.
Low-rank adaptation (LoRA; Hu et al., 2022) freezes the pretrained matrix and learns a low-rank correction:
A full update of one matrix has parameters; the two factors have :
The update has rank at most , because its column space lies inside that of :
Gradients flow only into the factors. With for one input:
At the first step , so : only moves at first, and starts learning once . Optimizer state is kept only for and , and the frozen can even be stored in 4 bits: QLoRA fine-tuned a 65-billion-parameter model on a single 48 GB GPU (Dettmers et al., 2023).
import torch
import torch.nn as nn
class LoRALinear(nn.Module):
"""Wraps a frozen nn.Linear (weight W0 of shape d_out x d_in) with a rank-r update."""
def __init__(self, base: nn.Linear, r: int = 8, alpha: float = 16.0):
super().__init__()
self.base = base.requires_grad_(False) # W0 and bias stay frozen
d_out, d_in = base.weight.shape
self.A = nn.Parameter(torch.randn(r, d_in) * 0.01) # random
self.B = nn.Parameter(torch.zeros(d_out, r)) # zero: BA = 0 at the start
self.scale = alpha / r
def forward(self, x): # x: (..., d_in)
return self.base(x) + self.scale * (x @ self.A.T) @ self.B.TA drop-in replacement for a linear layer; only and are handed to the optimizer. Hu et al. applied it to the attention projections and ; for GPT-3 they reported 10,000 times fewer trainable parameters and a third of the GPU memory of full fine-tuning, matching its quality on their benchmarks.
A model has 32 layers, each with query and value projections of size . LoRA with is applied to both projections in every layer. How many trainable parameters is that, in millions?
Show the answer
4.2 million
Each matrix gets parameters, and matrices give million, against about 1.07 billion weights in those projections (0.39%). Small enough that many task-specific adapters can share one frozen base model.
Why should a low-rank update suffice? Aghajanyan, Zettlemoyer & Gupta (2021) found that fine-tuning pretrained models still works when the update is confined to a random subspace of very low dimension: on some tasks a few hundred parameters reached 90% of full fine-tuning's performance. The pretrained network already contains the features; fine-tuning mostly recombines them. Other parameter-efficient methods insert small bottleneck MLPs after each sublayer (adapters; Houlsby et al., 2019) or learn a few virtual token embeddings while every weight stays frozen (prefix and prompt tuning; Li & Liang, 2021; Lester et al., 2021).
Learning a reward from comparisons
People are inconsistent at scoring a response on an absolute scale but fairly reliable at saying which of two is better. So labelers see a prompt and two responses and pick the winner over the loser . The Bradley–Terry model (1952) explains such choices with a latent score , the reward:
The reward model is typically the SFT network with its vocabulary head replaced by a single scalar output. Maximize the likelihood of the observed comparisons, that is, minimize
With and :
This is logistic regression on the difference of two scores: pairs the model already ranks confidently () contribute almost nothing, misranked pairs the most. A ranking of responses supplies every pair; InstructGPT's 4 to 9 responses gave 6 to 36 comparisons per prompt.
Two facts matter later. The loss sees rewards only through differences between responses to the same prompt, so is identified only up to a function of the prompt alone. And the labels are noisy: InstructGPT's labelers agreed with each other on about 73% of comparisons. The reward model is a noisy, finite-sample summary of human judgment, accurate mainly on responses like those it was trained on.
Reward model B outputs , where depends only on the prompt. How do A and B differ?
- B predicts every comparison with more confidence
- They assign identical probabilities to every comparison, so no preference data can tell them apart
- B prefers longer responses
- A is better calibrated, because B's scores are shifted
Show the answer
B. They assign identical probabilities to every comparison, so no preference data can tell them apart
Both responses in a comparison share the prompt, so cancels in . Rewards are meaningful only as differences within a prompt, which is why implementations often normalize them, for example to zero mean.
RL on a KL leash
Now maximize the learned reward, but not too hard. is a proxy, trained on SFT-like responses, and a policy that drifts far from them finds responses the proxy overrates. RLHF therefore penalizes the KL divergence from the SFT model, now called the reference :
Fix a prompt and drop from the notation. Write the objective as one sum over responses:
Normalize the denominator into a distribution with the partition function :
, with equality only at , so is the unique maximizer and the optimal value is . The reward tilts the reference distribution:
Limits: returns , and puts all the mass on the highest-reward responses that can produce. In between, probability moves toward high reward by the factor , never onto responses the reference rules out.
The sum over all responses is intractable, so is approximated by PPO (Schulman et al., 2017), a policy-gradient method: sample responses, score them, and take clipped gradient steps (Policy Gradients & Actor–Critic). The KL penalty is spread over tokens, since :
input: SFT policy π_ref, reward model r_φ, prompts D, KL weight β, clip range ε
π_θ ← π_ref; value head V_ψ ← initialized from r_φ
repeat
sample prompts x ~ D and responses y ~ π_θ(· | x)
for each token t of y: # per-token reward
R_t ← −β · (log π_θ(y_t | x, y_<t) − log π_ref(y_t | x, y_<t))
R_T ← R_T + r_φ(x, y) # sequence reward at the end
 ← advantages from R and V_ψ (generalized advantage estimation)
π_old ← π_θ
for a few epochs over this batch:
ρ_t ← π_θ(y_t | x, y_<t) / π_old(y_t | x, y_<t)
ascend Σ_t min(ρ_t Â_t, clip(ρ_t, 1 − ε, 1 + ε) Â_t); regress V_ψ on the returns
until the held-out reward stops improving or the KL budget is spentRLHF with PPO in the style of InstructGPT, which also mixed pretraining gradients into the update to limit regressions on standard NLP benchmarks. Four networks are in play: policy, reference, reward model and value function.
The SFT model assigns probability exactly to some response that the reward model scores very highly. What probability does the KL-regularized optimum give it?
- Close to 1, if is small enough
- Exactly , for every
- It depends on the rewards of the other responses
Show the answer
C. Exactly , for every
: a policy that puts mass where the reference has none pays an infinite KL penalty. Softmax policies never assign exactly zero, but the lesson survives: for to overtake a response , it needs a reward advantage of at least . RLHF reweights what the starting model can already say.
Skipping the reward model: DPO, and what can go wrong
The closed form invites a shortcut (Rafailov et al., 2023). Solve it for the reward: . Every reward corresponds to the policy it induces, and the intractable depends only on the prompt, exactly the part of a reward that comparisons cannot see.
Substitute this reward into the Bradley–Terry model. Both responses share the prompt, so cancels:
Parametrize by the policy itself and maximize the likelihood of the preference data:
A supervised loss on fixed data: no sampling during training, no separate reward model, no value network. The policy is its own reward model, , and the gradient raises and lowers , weighted by how badly the implicit reward misranks the pair:
| Aspect | PPO-based RLHF | DPO |
|---|---|---|
| Training data | prompts, with responses sampled from the current policy (on-policy) | a fixed set of preference pairs (offline) |
| Networks in memory | policy, reference, reward model, value function | policy, reference |
| Reward | explicit; can score any new response | implicit, |
| Main weakness | complex and sensitive to hyperparameters | sees only the responses in its dataset |
Human labels are slow and costly, so models also label for models. In Constitutional AI (Bai et al., 2022), a model critiques and revises its own responses against a short list of written principles, and in the RL stage a model, not a person, picks the better of two responses: reinforcement learning from AI feedback (RLAIF). Whether such techniques yield systems that do what people actually intend is the subject of AI Safety & Alignment.
Context at inference time, and how to evaluate
Fine-tuning changes weights; prompting changes the input. A system prompt sets the role, a few worked examples in the prompt define a task (in-context learning; see Large Language Models: Pretraining & Scaling), and asking for intermediate steps elicits a chain of thought (Neurosymbolic AI & Reasoning Models). None of this adds knowledge: a model's weights are a frozen, lossy summary of its training data, one source of hallucinations.
Retrieval-augmented generation (Lewis et al., 2020) adds knowledge at query time. Split a corpus into passages and embed each with an encoder . For a query , retrieve the passages with the highest cosine similarity , or the best lexical matches, and put them into the prompt. Knowledge can be updated without retraining, and answers can cite their sources.
Finally, how do you know any of this worked? Benchmarks with reference answers are cheap, but their items leak into web-scale training data (contamination). Open-ended answers need human or model judges, whose verdicts are noisy and biased. And pairwise votes between models are aggregated with the same Bradley–Terry model as the reward model. Each of these needs statistics, not just a leaderboard.
Key takeaways
- Post-training turns a pretrained policy into an assistant: supervised fine-tuning on demonstrations, a reward model trained on comparisons, then KL-regularized reinforcement learning.
- LoRA learns with instead of trainable parameters per matrix (0.39% for , ) and merges into at no inference cost.
- Bradley–Terry turns comparisons into a reward, , identified only up to a per-prompt shift.
- The KL-regularized optimum is ; DPO inverts it into a preference loss on log-ratios. Optimizing a proxy reward too hard backfires (overoptimization, sycophancy).
- Prompting and retrieval supply context at inference time without changing weights; retrieval keeps knowledge current and citable.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
In LoRA, why is initialized to zero while is random?
- So that and training starts exactly from the pretrained model
- So that the update has rank exactly from the start
- To keep and orthogonal during training
- Because zero initialization makes inference faster
Show the answer
A. So that and training starts exactly from the pretrained model
With , : the adapted model initially computes exactly what the pretrained one does. The random matters too: if both factors were zero, both gradients would vanish, since and .
A reward model gives and . Under Bradley–Terry, what is the probability that a labeler prefers ?
- , the ratio of the rewards
- , since has the higher reward
Show the answer
B.
. Only the difference matters, and a higher reward makes a response more likely, not certain, to win.
You double the KL coefficient in RLHF. What happens to the optimal policy ?
- It moves further from the reference model and earns more reward
- Nothing: only rescales the objective
- It becomes deterministic
- It moves closer to the reference model, with lower expected reward and lower KL divergence
Show the answer
D. It moves closer to the reference model, with lower expected reward and lower KL divergence
: a larger flattens the tilt, so stays closer to . sets the exchange rate between reward and divergence.
What lets DPO train without ever computing the partition function ?
- for language models
- It is estimated by sampling responses from the policy
- It depends only on the prompt, so it cancels in the reward difference between two responses to that prompt
- DPO uses a so large that is negligible
Show the answer
C. It depends only on the prompt, so it cancels in the reward difference between two responses to that prompt
, and Bradley–Terry uses only , in which appears twice with opposite signs.
An assistant must answer questions about internal documents that change every week. Which approach fits best?
- Fine-tune the model on the documents once
- RLHF with labelers who know the documents
- Lower the sampling temperature
- Retrieval-augmented generation over an index of the current documents
Show the answer
D. Retrieval-augmented generation over an index of the current documents
Retrieval puts the current text into the prompt at query time: updating the index updates the answers, and the model can cite its sources. Fine-tuning bakes in a snapshot that goes stale.
Go deeper
- RLHF & Preference Optimization · Reward models, PPO and direct preference optimization.
- Prompting, Retrieval & Tool Use · Giving models context, memory and actions.
- Evaluating Language Models · Benchmarks, contamination and human judgment.
Further reading
- L. Ouyang et al., "Training language models to follow instructions with human feedback," NeurIPS (2022).
- E. J. Hu et al., "LoRA: Low-rank adaptation of large language models," ICLR (2022).
- R. Rafailov, A. Sharma, E. Mitchell, S. Ermon, C. D. Manning & C. Finn, "Direct preference optimization: Your language model is secretly a reward model," NeurIPS (2023).
- P. Lewis et al., "Retrieval-augmented generation for knowledge-intensive NLP tasks," NeurIPS (2020).