QuiddityML

By · 26 November 2026 · 8 min read

DPO vs RLHF

Where the DPO loss comes from, what DPO gives up next to RLHF and how to write the loss in PyTorch, with a worked example you can check by hand.

Direct preference optimization (DPO) trains a language model on pairs of a preferred answer and a rejected answer with one loss function, the way ordinary supervised learning trains on labeled examples. It aims for the same result as reinforcement learning from human feedback (RLHF), which is moving a chat assistant toward answers people prefer. DPO gets there without a separate reward model and without a reinforcement learning loop, so it is usually simpler to run.

Language models read and write text as tokens, which are whole words or pieces of words. Both methods start from a model that has already been pretrained and then fine-tuned on written examples of good responses, a step called supervised fine-tuning (SFT).

How RLHF works

Both methods learn from the same kind of data. Each record has a prompt, a chosen response that people preferred and a rejected response.

RLHF uses that data in two stages. First it trains a reward model, a separate network that takes a prompt $x$ and a response $y$ and returns a score $r(x, y)$. The scores are trained so that $\sigma\big(r(x, y_w) - r(x, y_l)\big)$ is close to 1, where $y_w$ is the chosen response, $y_l$ the rejected one and $\sigma$ the sigmoid function $\sigma(z) = 1/(1+e^{-z})$. This way of turning two scores into a probability is the Bradley-Terry model.

Then reinforcement learning updates the SFT model, which is called the policy. The policy generates responses, the reward model scores them and the update makes high-scoring responses more likely. A frozen copy of the SFT model, the reference model, adds a penalty when the policy's probabilities drift too far from its own. That penalty is a KL divergence, a number that measures how different two probability distributions are. Many RLHF setups also train a value model that helps the reinforcement learning optimizer.

That makes four models at once, a lot of memory and a training loop that can become unstable if the penalty weight or the learning rate is off.

Why RLHF is hard: the policy being trained and the frozen reference run at once with a reward model that scores responses and a value model that estimates expected quality. That means more memory and a training loop that can go unstable.

What DPO changes

DPO keeps the goal of moving toward preferred responses. It drops the separate reward model and the loop where the policy samples responses during training. What remains is one loss over chosen and rejected pairs, trained with backpropagation like any supervised model.

RLHF needs four models in memory and an RL loop. DPO needs a policy and a frozen reference, trained with a supervised loss on preference pairs. The reward model and the RL loop both drop out.

Where the DPO loss comes from

DPO starts from the objective RLHF optimizes. Here $\pi_\theta(y \mid x)$ is the probability the policy gives to response $y$ for prompt $x$, $\pi_{\text{ref}}$ is the same for the frozen reference, and $\beta$ sets how strongly drift from the reference is penalized. RLHF looks for the policy with the highest average reward minus a KL penalty:

$$\max_{\pi_\theta} \; \mathbb{E}_{y \sim \pi_\theta}\big[r(x, y)\big]$$

$$- \beta \, D_{KL}\big(\pi_\theta \,\|\, \pi_{\text{ref}}\big)$$

The DPO derivation shows that this objective has a closed-form optimal policy, meaning an exact formula instead of something found by training. Call it $\pi^*$:

$$\pi^*(y \mid x) = \frac{1}{Z(x)} \, \pi_{\text{ref}}(y \mid x)$$

$$\cdot \exp\!\Big(\frac{r(x, y)}{\beta}\Big)$$

In words, the best policy takes the reference model's probability for each response and multiplies it by $e^{r/\beta}$, so responses with higher reward get more probability. It then divides by $Z(x)$, a normalizing term that makes the probabilities for one prompt add up to 1.

Take the log of both sides and solve for the reward. The reward can then be written in terms of the policy itself:

$$r(x, y) = \beta \log \frac{\pi^*(y \mid x)}{\pi_{\text{ref}}(y \mid x)}$$

$$+ \beta \log Z(x)$$

The log of the fraction is called a log-ratio: how much more or less likely the policy makes a response than the reference does. It is positive when the policy gives the response more probability than the reference and negative when it gives less.

You can check this with small numbers. Take $\beta = 0.2$, $\pi_{\text{ref}}(y \mid x) = 0.01$, $r(x, y) = 1$ and $Z(x) = 2$. The first formula gives $\pi^*(y \mid x) = 0.01 \times e^{5} / 2 \approx 0.742$. Put that into the second formula and you get $0.2 \log 74.2 + 0.2 \log 2 \approx 0.861 + 0.139 = 1.0$, the reward you started with.

The closed-form optimal policy, then the same statement solved for the reward r. Z(x) sums over every possible output. The reward is written from the policy itself, without a separate reward network.

Why the partition function cancels

$Z(x)$ is called the partition function. To compute it you would have to sum over every possible response to the prompt, which is far too many to list. If the loss needed $Z(x)$, the formula above would be of no use.

The Bradley-Terry model only needs the difference between two rewards for the same prompt. Both rewards contain the same $\beta \log Z(x)$ term, because $Z$ depends only on the prompt. Subtract one reward from the other and that term cancels. In the example above, $\beta \log Z(x) \approx 0.139$ is added to the chosen reward and to the rejected reward alike, so their difference does not change.

Each reward is written as beta times its log ratio plus beta log Z(x). Subtracting the rejected reward from the chosen one cancels the two beta log Z(x) terms, so the intractable term does not have to be computed.

The DPO loss

Put the reward expression into the Bradley-Terry loss, $-\log \sigma$ of the reward difference, and cancel $Z(x)$. Write the policy being trained as $\pi_\theta$ in place of $\pi^*$. The result is the DPO loss on one chosen and rejected pair:

$$L_{\text{DPO}} = -\log \sigma\Big(\beta \log \frac{\pi_\theta(y_w \mid x)}{\pi_{\text{ref}}(y_w \mid x)}$$

$$- \beta \log \frac{\pi_\theta(y_l \mid x)}{\pi_{\text{ref}}(y_l \mid x)}\Big)$$

In words, the loss raises the policy's probability of the chosen response and lowers it for the rejected one, both measured relative to the reference model. The loss needs no reward model and no responses sampled during training.

Each $\beta \log$ term is $\beta$ times a log-ratio. For example, say the chosen response has a log-ratio of $+0.9$ and the rejected response $-0.4$, with $\beta = 0.2$. The margin inside the sigmoid is $0.2 \times (0.9 - (-0.4)) = 0.26$. The loss is $-\log \sigma(0.26) \approx 0.57$, a little below the $-\log 0.5 \approx 0.69$ you get at a margin of 0.

Chosen log-ratio +0.9 and rejected log-ratio -0.4 with beta 0.2 give a margin of 0.26. On the curve of loss against margin, the loss at margin 0 is 0.69 and the point (0.26, 0.57) sits slightly to its right. The reward model and RL loop are gone, leaving one loss to backprop.

The implicit reward

DPO trains no reward model, but a reward is still inside the loss. The implicit reward DPO gives a response is $\beta$ times its log-ratio:

$$\hat{r}(x, y) = \beta \log \frac{\pi_\theta(y \mid x)}{\pi_{\text{ref}}(y \mid x)}$$

In the example, the chosen response has an implicit reward of $0.2 \times 0.9 = 0.18$ and the rejected one $0.2 \times (-0.4) = -0.08$. Their difference is the margin of 0.26. Raising a response's probability under the policy, relative to the reference, raises its implicit reward. The reference does a job close to the KL penalty in RLHF, since it measures how far the policy has moved from where it started.

The implicit reward is beta times log of pi_theta(y|x) over pi_ref(y|x). Higher policy probability relative to the reference means a higher implicit reward. No separate reward model is trained.

DPO in PyTorch

A response's log-probability is the sum of the log-probabilities of its tokens. The function below takes those sums for the chosen and rejected responses under the policy and under the reference. The numbers reproduce the example above, and backward() shows which way the gradient pushes each log-probability:

1import torch
2import torch.nn.functional as F
3 
4def dpo_loss(pi_chosen, pi_rejected, ref_chosen, ref_rejected, beta=0.2):
5    chosen_ratio = pi_chosen - ref_chosen        # log pi/pi_ref for the chosen response
6    rejected_ratio = pi_rejected - ref_rejected  # log pi/pi_ref for the rejected response
7    margin = beta * (chosen_ratio - rejected_ratio)
8    return -F.logsigmoid(margin).mean(), margin
9 
10# log-probabilities of whole responses (sums over their tokens)
11pi_chosen = torch.tensor([-12.1], requires_grad=True)
12pi_rejected = torch.tensor([-15.4], requires_grad=True)
13ref_chosen = torch.tensor([-13.0])    # the frozen reference gets no gradient
14ref_rejected = torch.tensor([-15.0])
15 
16loss, margin = dpo_loss(pi_chosen, pi_rejected, ref_chosen, ref_rejected)
17loss.backward()
18print("margin:", round(margin.item(), 2))
19print("loss:", round(loss.item(), 2))
20print("grad on chosen log-prob:", round(pi_chosen.grad.item(), 3))
21print("grad on rejected log-prob:", round(pi_rejected.grad.item(), 3))
1margin: 0.26
2loss: 0.57
3grad on chosen log-prob: -0.087
4grad on rejected log-prob: 0.087

Here the chosen log-ratio is $-12.1 - (-13.0) = 0.9$ and the rejected one is $-15.4 - (-15.0) = -0.4$. Gradient descent moves each value against its gradient, so the chosen log-probability goes up and the rejected one goes down. In real training the four inputs come from running the policy and the reference model on each pair, and the gradient flows back into the policy's weights. F.logsigmoid computes $\log \sigma$ in a numerically stable way. If training makes the chosen responses less likely, check first that the chosen and rejected columns are not swapped.

A simplified DPO step: a preference pair of prompt, chosen and rejected goes through the updated policy and the frozen reference. Each step computes chosen_ratio, rejected_ratio, margin = beta * difference and loss = -logsigmoid(margin). No reward model and no sampling loop.

DPO vs RLHF side by side

RLHF DPO
Models in memory four two
Reward model trained separately none, implicit in the loss
Training loop reinforcement learning updates one supervised loss
Data can score fresh samples during training fixed preference set

DPO caught on because it is usually simpler to run than RLHF and can be competitive in quality. During training it keeps only the policy and the frozen reference in memory.

The tradeoff is the data. DPO learns from a fixed, offline preference dataset collected before training. Depending on the setup, RLHF can generate fresh responses from the current policy and score them with the reward model during training, which is called online sampling. DPO gives up that loop in exchange for the simpler training step.

RLHF keeps four models in memory, uses an RL update and can score fresh samples online. DPO keeps two, uses a supervised loss and trains on a fixed preference set. DPO is usually simpler to run and can be competitive.

Which one to use and common mistakes

DPO is a common first choice when you already have a dataset of chosen and rejected pairs and want a training step that looks like ordinary fine-tuning. RLHF fits better when scoring new responses from the current policy during training is something you need, since that online loop is what DPO gives up.

Mistakes that come up:

RLHF explained covers the reward model, the Bradley-Terry loss and the KL penalty step by step. Both methods start from the model built in instruction tuning and SFT, and pretraining vs post-training shows where all of these stages fit. The sigmoid inside the DPO loss is the same one used in logistic regression. How to check whether DPO or RLHF helped is in how LLM alignment is evaluated.

QuiddityML teaches DPO as its own concept in the Intro to NLP track, where the exercises go from matching the DPO loss to its equation and tracing it for one pair to writing dpo_loss from scratch.