4.4.1Alignment, Prompting & RAG

Reinforcement Learning from Human Feedback (RLHF)

2,162 words10 min readdifficulty · medium3 backlinks

WHAT is RLHF?

The big idea: preferences are cheaper and more reliable than absolute scores. A human is bad at saying "this answer is a 7.3/10" but good at saying "answer A is better than answer B."


WHY not just do more supervised learning?


Figure — Reinforcement Learning from Human Feedback (RLHF)

Stage 1 — Supervised Fine-Tuning (SFT)

WHAT: Fine-tune the base LM on a dataset of (prompt, ideal human answer) pairs with ordinary cross-entropy.

WHY: The base model predicts internet text, not helpful assistant replies. SFT gives a sane starting policy πSFT\pi^{\text{SFT}} that already talks like an assistant, so RL has a decent place to start (RL from scratch on language would be hopeless).


Stage 2 — The Reward Model (derived from scratch)

WHAT: Given a prompt xx and two responses ywy_w (winner) and yly_l (loser), a labeler picks the better one. We want a scalar model rθ(x,y)r_\theta(x,y) such that better answers get higher reward.

HOW do we turn "A beats B" into a loss? We use the Bradley–Terry model of pairwise comparisons. Suppose each response has a latent "quality" rr. Bradley–Terry says the probability a human prefers ywy_w over yly_l is a logistic function of the reward difference:

P(ywylx)=erθ(x,yw)erθ(x,yw)+erθ(x,yl)P(y_w \succ y_l \mid x) = \frac{e^{r_\theta(x,y_w)}}{e^{r_\theta(x,y_w)} + e^{r_\theta(x,y_l)}}

Why this form? Divide top and bottom by erθ(x,yw)e^{r_\theta(x,y_w)}... let's instead factor to reveal the sigmoid. Divide numerator and denominator by erθ(x,yw)e^{r_\theta(x,y_w)}:

P=11+e(rθ(x,yw)rθ(x,yl))=σ(rθ(x,yw)rθ(x,yl))P = \frac{1}{1 + e^{-(r_\theta(x,y_w) - r_\theta(x,y_l))}} = \sigma\big(r_\theta(x,y_w) - r_\theta(x,y_l)\big)

Why this step? It shows the model only cares about the difference of rewards — exactly what a comparison gives us. The absolute scale is unidentified (adding a constant to all rewards changes nothing), which is fine.

Now maximize the likelihood of the observed human choices → minimize negative log-likelihood:

The RM is usually the SFT model with the final token-prediction head replaced by a single scalar head on the last token.


Stage 3 — RL optimization with PPO

WHAT: Treat the LM as a policy πϕ(yx)\pi_\phi(y\mid x). Sample a response, score it with the RM, and update ϕ\phi to increase expected reward.

The naive objective: maxϕ  Ex,  yπϕ[rθ(x,y)]\max_\phi \; \mathbb{E}_{x,\;y\sim\pi_\phi}\big[\,r_\theta(x,y)\,\big]

WHY this is dangerous: The RM is only accurate near data it saw. If we push hard on pure reward, the policy finds adversarial gibberish that fools the RM (reward hacking). So we add a leash back to the SFT policy.

WHY the KL term (derivation of intuition): We want high reward but stay close to a trusted model. Rewrite the per-token reward as r(x,y)=rθ(x,y)βlogπϕπSFTr'(x,y) = r_\theta(x,y) - \beta\log\frac{\pi_\phi}{\pi^{\text{SFT}}}. If πϕ\pi_\phi drifts far from πSFT\pi^{\text{SFT}}, the log-ratio blows up and eats the reward. This keeps generations fluent and prevents mode collapse.

HOW does PPO update the policy? PPO maximizes reward while limiting how far each update moves the policy, using the clipped surrogate objective. With ratio ρt=πϕ(atst)πϕold(atst)\rho_t = \frac{\pi_\phi(a_t|s_t)}{\pi_{\phi_{\text{old}}}(a_t|s_t)} and advantage AtA_t:

LPPO=E[min(ρtAt,  clip(ρt,1ϵ,1+ϵ)At)]\mathcal{L}^{PPO} = \mathbb{E}\Big[\min\big(\rho_t A_t,\; \text{clip}(\rho_t, 1-\epsilon, 1+\epsilon)A_t\big)\Big]

Why clip? A single big update on a noisy reward can destroy the policy. Clipping removes the incentive to move ρt\rho_t beyond [1ϵ,1+ϵ][1-\epsilon,1+\epsilon], giving small, safe steps.


Worked Example 1 — Reward-model loss numerically

Suppose for one comparison rθ(x,yw)=2.0r_\theta(x,y_w) = 2.0 and rθ(x,yl)=0.5r_\theta(x,y_l) = 0.5.

  • Step: difference Δ=2.00.5=1.5\Delta = 2.0 - 0.5 = 1.5. Why? RM only sees the gap.
  • Step: σ(1.5)=11+e1.50.8176\sigma(1.5) = \frac{1}{1+e^{-1.5}} \approx 0.8176. Why? Probability we predicted the winner correctly.
  • Step: loss =log(0.8176)0.201= -\log(0.8176) \approx 0.201. Why? Low loss because the model already ranked the winner higher; gradient will still gently widen the gap.

If instead the model was wrong (rw=0.5,rl=2.0r_w=0.5, r_l=2.0): σ(1.5)0.182\sigma(-1.5)\approx0.182, loss =log(0.182)1.70=-\log(0.182)\approx1.70 — much bigger, pushing a strong correction. This is exactly what we want.

Worked Example 2 — The KL leash in action

Say for a token the SFT model gives probability 0.100.10 to a word and the current policy gives 0.400.40.

  • Log-ratio =log(0.40/0.10)=log41.386= \log(0.40/0.10) = \log 4 \approx 1.386.
  • With β=0.2\beta = 0.2, penalty =0.2×1.3860.277= 0.2 \times 1.386 \approx 0.277 subtracted from the reward.
  • Why this step? The policy got 4× more confident than the trusted model on this token; the penalty says "only do that if the reward gain clearly beats 0.2770.277."

Common mistakes


Recall Feynman: explain it to a 12-year-old

Imagine teaching a puppy tricks. You can't explain in English what "good behavior" means, but you can point at two tricks and say "that one was better." You give a treat-predicting judge (the reward model) lots of these comparisons until it learns to guess which trick you'd like. Then you let the puppy try things, the judge hands out pretend-treats, and the puppy learns to do more of what earns treats. But you keep the puppy on a leash (KL penalty) so it doesn't run off doing weird stuff just to trick the judge. That leashed treat-training is RLHF.


Active-recall flashcards

#flashcards/ai-ml

What are the 3 stages of RLHF, in order?
(1) Supervised Fine-Tuning (SFT), (2) train a Reward Model from human preference comparisons, (3) RL optimization with PPO + KL penalty.
Why use pairwise comparisons instead of absolute quality scores?
Humans give noisy absolute ratings but reliable relative judgments ("A > B"); comparisons are cheaper and more consistent.
Write the reward-model loss and its origin.
E[logσ(rθ(x,yw)rθ(x,yl))]-\mathbb{E}[\log\sigma(r_\theta(x,y_w)-r_\theta(x,y_l))], derived from the Bradley–Terry model + maximum likelihood.
Why does the RM only depend on the difference of rewards?
The Bradley–Terry probability simplifies to σ(rwrl)\sigma(r_w - r_l); adding a constant to all rewards leaves the loss unchanged (scale is unidentified).
What is the full RLHF RL objective?
maxϕEyπϕ[rθ(x,y)βlogπϕ(yx)πSFT(yx)]\max_\phi \mathbb{E}_{y\sim\pi_\phi}[r_\theta(x,y) - \beta\log\frac{\pi_\phi(y|x)}{\pi^{SFT}(y|x)}] — reward minus a KL penalty to the SFT policy.
Why include the KL penalty?
To keep the policy close to the trusted SFT model, preserving fluency/diversity and preventing reward hacking / mode collapse.
What is reward hacking (Goodhart) in RLHF?
The policy exploits inaccuracies of the proxy reward model, producing outputs that score high but are actually bad.
What does PPO's clipping accomplish?
It limits how far each update moves the policy (ratio kept near 1), giving small stable steps and avoiding destructive updates from noisy rewards.
Does RLHF add new knowledge?
Mostly no — it reshapes/prioritizes behaviors the base model already had; it doesn't teach new facts.
What architecture is the reward model usually?
The SFT model with its token head replaced by a single scalar reward head on the final token.

Connections

Concept Map

hard to score absolutely

Stage 1 SFT

starting policy

Stage 2 train

defines loss

logistic of reward diff

scores outputs

optimized via

constrained by

prevents

produces

Human Preferences

Pairwise Comparisons A vs B

Pretrained Base LM

SFT Policy pi_SFT

Stage 3 RL Optimization

Reward Model r_theta

Bradley-Terry Model

Sigmoid of reward difference

PPO Algorithm

KL Penalty to SFT

Reward Gaming / Gibberish

Aligned LM

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Dekho, RLHF ka core problem yeh hai: "helpful, harmless aur honest bano" — iske liye koi seedha formula nahi likh sakte. To hum kya karte hain? Humans ko do jawab dikhate hain aur poochte hain "in dono me kaunsa better hai?" Absolute rating (jaise 7/10) dena insaan ke liye mushkil hai, par comparison ("A behtar hai B se") dena easy aur reliable hai. Yehi trick hai.

Pipeline teen steps ka hai. Pehle SFT: base model ko human-written accha jawab dikha kar fine tune karo, taaki woh assistant ki tarah baat kare. Phir Reward Model: preference comparisons se ek chhota model train karo jo bata de ki human kis jawab ko pasand karega. Iski loss Bradley-Terry se aati hai — logσ(rwrl)-\log\sigma(r_w - r_l) — matlab model sirf winner aur loser ke reward ke difference ki parwah karta hai. Teesra, PPO: language model ko policy maan kar RL se train karo, reward model score badhane ke liye.

Sabse important cheez hai KL penalty (the leash). Agar tum sirf reward maximize karoge, model "reward hacking" kar dega — aisa bakwaas output banayega jo reward model ko chakma de de, par actually ghatiya ho. Isliye KL term policy ko SFT model ke paas rok kar rakhta hai. Ek baat yaad rakho: RLHF naya gyaan nahi sikhata, woh sirf pehle se maujood behaviors ko re-prioritize karta hai — accha wala upar, bura wala neeche. Yeh matter isliye karta hai kyunki yehi technique ChatGPT jaise models ko "aligned" aur useful banati hai.

Go deeper — visual, from zero

Test yourself — Alignment, Prompting & RAG

Connections