On this page
Your candidate raises internal reward-model score by +0.31, yet wins only 184 of 400 blinded human comparisons while growing 48 tokens longer and prepending "Verified answer:". Would you ship it?
That divergence between proxy score and human preference defines alignment engineering. On our Python softmax(z) overflow question, subtracting max(z) before exp(z) scored 1.80 while casting to float64 after exp(z) scored 0.70 (a 1.10 Bradley-Terry margin, ~75% win probability). Should you optimize the policy online against that reward model with RLHF, or directly on preference pairs with DPO?
What preference pairs add to SFT
SFT imitates demonstrations yet still leaves subtle bugs, verbosity, and miscalibrated refusals.[1] Pairwise preferences give the optimizer an explicit contrast on the exact same prompt (pushing "subtract max(z) before exp(z)" above "cast after exp(z)"), and comparing two outputs is faster to label than writing gold answers from scratch.

RLHF: a judge, then an actor
Classic RLHF runs three stages: SFT, reward modeling under Bradley-Terry loss , and online PPO optimizing expected reward minus a KL divergence penalty from the frozen SFT reference :[2][1][3]
For fixed and , factoring reveals an exact closed-form optimum (intractable to sample directly because sums over all strings, which PPO approximates via rollouts and DPO cancels algebraically[4]):
Token-level reward shaping and the four model roles
PPO coordinates four logical roles: trainable actor () and critic (), plus frozen reference () and reward model (). With four separate 70B backbones (16 B/param trainable, 2 B/param frozen), state alone takes 2,520 GB (1,120 each for actor/critic, 140 each for ref/reward); dropping the critic cuts 44.4% to 1,400 GB (in practice roles can share weights or use smaller critics, and frameworks like OpenRLHF support colocated or async rollout engines[5]).
We charge the per-token KL drift at every token and add at final token . Generalized Advantage Estimation (GAE) propagates terminal reward backward via and ( at true termination):[6]
def gae(rewards: list[float], values: list[float], lam: float, gamma: float = 1.0) -> list[float]:
adv, running = [0.0] * len(rewards), 0.0
for t in reversed(range(len(rewards))):
running = (rewards[t] + gamma * values[t + 1] - values[t]) + gamma * lam * running
adv[t] = running
return adv
for lam in (1.0, 0.5):
print(f"GAE lambda={lam:.1f} -> {gae([0.0, 0.0, 1.0], [0.0, 0.0, 0.0, 0.0], lam)}")
for name, rew, pi_lp, ref_lp in [("near_reference", 1.20, -2.1, -2.2), ("preamble_hack", 1.35, -1.2, -2.8)]:
print(f"{name:15s}: raw={rew:.2f}, log_ratio={pi_lp - ref_lp:+.1f}, shaped={rew - 0.20 * (pi_lp - ref_lp):.2f}")GAE lambda=1.0 -> [1.0, 1.0, 1.0]
GAE lambda=0.5 -> [0.25, 0.5, 1.0]
near_reference : raw=1.20, log_ratio=+0.1, shaped=1.18
preamble_hack : raw=1.35, log_ratio=+1.6, shaped=1.03![Three token transitions have rewards 0, 0, and 1. The critic predicts zero at all four states, including terminal V3, so the TD residuals are 0, 0, and 1. Backward GAE accumulation gives advantages [1, 1, 1] at lambda 1 and [0.25, 0.5, 1] at lambda 0.5; arrows point from the terminal decision toward earlier tokens.](https://assets.leetllm.com/v1/4eb6c21d24db/training/rlhf-dpo-aligning-language-models/illustrations/_generated/terminal_credit_assignment_dark.png)

What PPO actually clips
Across rollout-batch epochs, PPO forms ratio (denominator is the rollout snapshot , not ) and maximizes:
Clipping removes gradient incentive past when or below when , while leaving harmful moves fully penalized (it is not a hard clamp on probabilities or KL).
def surrogate(ratio: float, advantage: float, epsilon: float = 0.2) -> float:
return min(ratio * advantage, min(max(ratio, 1 - epsilon), 1 + epsilon) * advantage)
for advantage in (1.0, -1.0):
print(f"A={advantage:+.0f} at [0.5, 1.0, 1.5] -> {[round(surrogate(r, advantage), 2) for r in (0.5, 1.0, 1.5)]}")A=+1 at [0.5, 1.0, 1.5] -> [0.5, 1.0, 1.2]
A=-1 at [0.5, 1.0, 1.5] -> [-0.8, -1.0, -1.5]
DPO: turn reward fitting into policy fitting
Why an offline loss can stand in for RL
Solving the closed-form optimal policy for gives . Substituting into Bradley-Terry cancels identically, defining implicit reward and the DPO objective:[4]
Differentiating produces a hard-pair-weighted push-pull update:
Notice the dual role of : for fixed preference odds over a uniform reference, the ideal optimal policy has odds (so larger stays closer to ), while at initialization () the loss slope for one observed vote is (larger scales initial gradient magnitude up).
Computing DPO from token logits
On our softmax(z) pair, suppose summed response log-probabilities are chosen (-8.2 policy, -8.5 ref) and rejected (-9.5 policy, -9.1 ref) with : the chosen log-ratio is +0.3, the rejected log-ratio is -0.4, the margin is +0.7, the scaled logit is 0.07, and the DPO loss is .
Sum response log-probabilities across response tokens plus EOS only, shifting logits by one and masking prompt and padding positions by index (never by token ID, since 0 can be valid content):
import torch
import torch.nn.functional as F
chosen_ids = torch.tensor([0, 2, 1, 2, 4, 0])
rejected_ids = torch.tensor([0, 2, 3, 0, 4, 0])
attn_mask = torch.tensor([1, 1, 1, 1, 1, 0], dtype=torch.bool)
prompt_len, beta = 2, 0.1
chosen_pi = torch.tensor([
[0.0]*5, [0.0, 2.4, 0.1, -0.8, -1.0], [0.0, 0.2, 2.1, -0.6, -1.0],
[0.0, 0.0, 0.0, 0.0, 2.0], [0.0]*5, [0.0]*5,
], requires_grad=True)
chosen_ref = torch.tensor([
[0.0]*5, [0.0, 0.8, 0.2, 0.0, -1.0], [0.0, 0.1, 0.9, 0.0, -1.0],
[0.0, 0.0, 0.0, 0.0, 2.0], [0.0]*5, [0.0]*5,
])
rejected_pi = torch.tensor([
[0.0]*5, [0.2, -0.4, -0.2, 1.1, -1.0], [1.0, -0.3, -0.4, 0.2, -1.0],
[0.0, 0.0, 0.0, 0.0, 2.0], [0.0]*5, [0.0]*5,
], requires_grad=True)
rejected_ref = torch.tensor([
[0.0]*5, [0.1, 0.0, 0.0, 0.6, -1.0], [0.7, 0.0, 0.0, 0.2, -1.0],
[0.0, 0.0, 0.0, 0.0, 2.0], [0.0]*5, [0.0]*5,
])
def response_logprob(logits: torch.Tensor, ids: torch.Tensor) -> torch.Tensor:
token_logp = F.log_softmax(logits[:-1], dim=-1).gather(-1, ids[1:].unsqueeze(-1)).squeeze(-1)
resp_mask = attn_mask[1:].clone()
resp_mask[: prompt_len - 1] = False
return (token_logp * resp_mask).sum()
c_logp, r_logp = response_logprob(chosen_pi, chosen_ids), response_logprob(rejected_pi, rejected_ids)
margin = (c_logp - response_logprob(chosen_ref, chosen_ids)) - (r_logp - response_logprob(rejected_ref, rejected_ids))
loss = -F.logsigmoid(beta * margin)
loss.backward()
print(f"chosen={c_logp.item():.3f}, rejected={r_logp.item():.3f}, margin={margin.item():.3f}, loss={loss.item():.3f}")
print("zero grad on prompt/pad:", chosen_pi.grad[0].abs().sum().item() == 0.0 and chosen_pi.grad[4].abs().sum().item() == 0.0)chosen=-0.993, rejected=-1.882, margin=0.640, loss=0.662
zero grad on prompt/pad: TrueLikelihood displacement and TRL setup
Because DPO maximizes the difference between chosen and rejected log-ratios, the margin can climb (0 -> +1.50) while both responses drop below reference likelihood (rejected simply falls faster), a phenomenon Razin et al. called likelihood displacement (DPOP adds a penalty when chosen drops below reference).[8][9] Monitor , , margin, and held-out generations together.
In TRL's DPOTrainer, precompute_ref_log_probs=True caches reference sums and valid target counts per (prompt, completion) so only one model stays in GPU memory,[10][11] meaning uncached completions cannot be scored against the freed reference later (pass all eval splits upfront and set max_length so differences aren't truncated).[7][12]
from trl import DPOConfig, DPOTrainer
trainer = DPOTrainer(
model=sft_checkpoint, processing_class=tokenizer,
args=DPOConfig(output_dir="runs/softmax-dpo", beta=0.1, precompute_ref_log_probs=True,
max_length=2048, learning_rate=5e-6, max_steps=200),
train_dataset=train_pairs, eval_dataset=eval_pairs,
)
trainer.train()Comparing RLHF and DPO
RLHF and DPO trade online exploration against simplicity:[1][4] PPO samples fresh completions every step (4 logical roles, rollout cost, reward hacking risk), whereas vanilla DPO optimizes a fixed offline pair set (2 roles, lower cost, vulnerable to stale pairs and unseen-response mass).

| Dimension | RLHF (PPO) | Vanilla DPO |
|---|---|---|
| Reward model | Separate trained scorer | Implicit in |
| Loop | On-policy RL with live rollouts | Offline pairwise classification |
| Logical roles | Actor, reference, reward, critic | Policy, reference (can precompute) |
| Online exploration | Yes: sees new failures it invents | No, unless pairs refresh iteratively |
| Primary risks | Reward hacking, critic noise, rollout cost | Stale pairs, unseen mass, displacement |
DPO's blind spot: the answer nobody compared
With three candidate answers (A correct, B buggy, unseen C buggy), any two policies keeping identical 4:1 A-to-B odds incur the exact same DPO loss even if unseen C absorbs 90% of probability mass:
from math import exp, log, log1p
ref = {"A": 1 / 3, "B": 1 / 3, "C": 1 / 3}
for name, pi in [("Policy 1", {"A": 0.40, "B": 0.10, "C": 0.50}), ("Policy 2", {"A": 0.08, "B": 0.02, "C": 0.90})]:
margin = log(pi["A"] / ref["A"]) - log(pi["B"] / ref["B"])
print(f"{name}: A/B odds={pi['A'] / pi['B']:.1f}, DPO loss={log1p(exp(-0.1 * margin)):.4f}, unseen C={pi['C']:.0%}")Policy 1: A/B odds=4.0, DPO loss=0.6262, unseen C=50%
Policy 2: A/B odds=4.0, DPO loss=0.6262, unseen C=90%
Iterative / Online DPO closes this gap without a critic by periodically sampling fresh pairs from the current policy, labeling them, and updating again.[13]
When the proxy lies
Returning to our opening candidate (+0.31 reward, +48 tokens, "Verified answer:" prefix, 184/400 human wins): check reward hacking (length gaming, sycophancy, format exploitation) with controlled rewrites, and remember DPO's 0.693 () step-0 loss is normal (if it stays stuck, check optimizer updates, contradictory labels, or truncation).
Never ship on internal reward alone. Gate promotion on blinded held-out human comparisons using a 95% Wilson CI (lower bound > 50%) plus a length-growth cap (+20 tokens):[14] 184/400 gives 46.0% with 95% Wilson CI [41.2%, 50.9%], failing both checks.

Compare related methods by training signal and system cost
| Method | Mechanism | Tradeoff |
|---|---|---|
| IPO[15] | Squared loss targeting finite margin (derivative ) | Curbs runaway margins on deterministic pairs |
| KTO[16] | Unpaired desirable/undesirable labels around (raising log-ratio lowers desirable loss, raises undesirable loss) | No pairs needed; sensitive to selection bias |
| ORPO[17] | SFT + odds-ratio penalty in one stage, no reference model | Saves reference VRAM; couples SFT and preference |
| SimPO[18] | Length-normalized average token log-prob + target margin, no reference | Cuts length bias; check completeness |
| GRPO[19][20] | Online RL without a critic: standardizes rewards across rollouts per prompt | Cuts critic VRAM; flat groups give zero advantage |
GRPO: group-relative advantage without a critic
GRPO samples completions per prompt, scores each, and standardizes within the group (), applying to every token inside a clipped surrogate plus a non-negative KL penalty ():[19][20]
When every rollout in a group earns the same reward, and all reward advantages collapse to 0.0 while any separate KL penalty stays active (TRL tracks frac_reward_zero_std and defaults beta=0.0 unless enabled).[21][22]
from math import exp
from statistics import mean, pstdev
def group_advantages(rewards: list[float]) -> list[float]:
mu, sigma = mean(rewards), pstdev(rewards)
return [0.0] * len(rewards) if sigma == 0 else [round((r - mu) / sigma, 3) for r in rewards]
def kto_loss(log_ratio: float, desirable: bool, beta: float = 0.5, z0: float = 0.2) -> float:
return 1 - 1 / (1 + exp(-(1 if desirable else -1) * beta * (log_ratio - z0)))
print("GRPO mixed:", group_advantages([1.0, 0.0, 0.5, 1.0]), "| flat:", group_advantages([1.0] * 4))
print("IPO (tau=0.1, target=5) at m=[0,5,10]:", [round((m - 5.0) ** 2, 1) for m in (0.0, 5.0, 10.0)])
print(f"KTO desirable 1->2: {kto_loss(1.0, True):.3f}->{kto_loss(2.0, True):.3f} | undesirable 1->2: {kto_loss(1.0, False):.3f}->{kto_loss(2.0, False):.3f}")GRPO mixed: [0.905, -1.508, -0.302, 0.905] | flat: [0.0, 0.0, 0.0, 0.0]
IPO (tau=0.1, target=5) at m=[0,5,10]: [25.0, 0.0, 25.0]
KTO desirable 1->2: 0.401->0.289 | undesirable 1->2: 0.599->0.711![Four completion rewards [1, 0, 0.5, 1] have population mean 0.625 and standard deviation about 0.4146. Subtracting the mean and dividing by the standard deviation yields signed advantages [+0.90, −1.51, −0.30, +0.90]. A uniform group [1, 1, 1, 1] has zero standard deviation and assigns zero reward advantage to every sample while a separate KL penalty remains active.](https://assets.leetllm.com/v1/ac974cd83ac3/training/rlhf-dpo-aligning-language-models/illustrations/_generated/grpo_group_advantages_dark.png)
Constitutional AI, RLAIF, and automated red teaming
Constitutional AI (CAI) scales safety alignment from a written constitution in two phases:[23][24]
- SL-CAI (critique-revision SFT): Elicit red-team draft , critique and revise against a principle into , and run SFT on only.
- RLAIF: Sample pairs from , extract soft AI-judge preferences averaged across swapped A/B orders to cancel position bias, fit a soft cross-entropy reward model (), and run RL alongside human helpfulness labels.[23][25]
Automated red teaming probes both single-turn and multi-turn escalations (such as Crescendo[26][27]) across held-out attack families. Always pair Attack Success Rate (ASR) with False Refusal Rate (FRR) on benign lookalikes, report unjudged coverage bounds rather than treating unresolved attempts as passes, and keep alignment separate from access control: enforce auth, tenant permissions, and tool validation in deterministic code backed by classifiers such as Llama Guard 4 or Constitutional Classifiers++.[28][29][30]