LLM Learning Roadmap
✨ Awesome-Anything
🖼️ Digital Image Processing
🍃 LLM Components
🌱 LLM Pre-training
☘️ LLM Post-Training
🍀 LLM Popular Models
🪴 LLM Applications
🌿 LLM Optimization
🌾 LLM Compression
🌵 LLM Hands-on Practice
🌴 LLM Must-read Papers
🌳 LLM Q&A
🐝 VLM Image Encoders
📝 MISC.
3.5 Direct Preference Optimization (DPO)
This article introduces DPO and detailed explanations of the algorithm
Why not classify DPO under the RLHF chapter?
Because RLHF is a reinforcement learning method, while DPO essentially drops the reinforcement learning part and instead directly optimizes using preference data. This turns it into more of a supervised optimization strategy based on preference data. Therefore, it's technically not a reinforcement learning method—at least there's no explicit reinforcement learning exploration process.

3.5.1 Limitations of RLHF-PPO
- Information loss from the two-stage training process: RLHF involves first
- training a reward model using preference data, then
- applying PPO or another reinforcement learning algorithm to fine-tune the model.
If the reward model itself is biased—say, if the reward signals don’t align well with human preferences—then the subsequent reinforcement learning phase can further amplify this bias and degrade model performance.
- High resource demands of PPO algorithms:
- Reinforcement learning typically requires a process of exploration and exploitation, which can be unstable. To stabilize PPO training, various tricks are often needed, which increases complexity and reduces training efficiency.
- Additionally, PPO still relies on four components: Actor, Critic, Reward, and Reference models. These components are standard in classic reinforcement learning environments, where the Actor and Critic handle the policy and value estimation, respectively, and Reference ensures reward stability. However, at the LLM scale, all these modules need to be fine-tuned based on LLM SFT models. This significantly increases the number of trainable parameters and the overall computational cost, as well as potential cumulative errors introduced by the four-model setup.
<ins/>
3.5.2 DPO Derivation
DPO is derived based on the Bradley-Terry preference model assumption and the goal of reinforcement learning. The DPO objective function eliminates the need for Reward and Critic models, directly optimizing for the preferred outcome.
Let’s start with the objective of Behavior-Regularized RL:
Where is the partition function.
Note that the is a common concept in reinforcement learning and probability modeling, especially in the derivation of maximum entropy (MaxEnt) strategy learning or inverse reinforcement learning. Intuitively, you can think of it as playing the role of a normalized constant (a.k.a. a partition function). It ensures that the new probability distribution defined is legal (i.e., all probability adds up to 1)
This partition function only depends on and (where are the prompt and response), and does not depend on the policy , so we can define:
It can be shown that this satisfies the definition of a valid probability distribution (non-negative and sums to 1), so the original objective can be rewritten as:
Therefore, we can directly obtain the optimal policy from the above objective:
From the above formula, we can derive the reward function that gives rise to the optimal policy:
If you remember the Bradley-Terry preference modeling we talked about earlier, by plugging the above expression into it, we get:
Here, denotes the logistic function (the most commonly used form of sigmoid function). Notably, due to the properties of the exponential function, the partition functions cancel out.
This means that our preference model ultimately only requires the reference policy and the policy to be optimized, and both the Critic and Reward models are no longer needed. Now we can directly optimize a strategy from preference data.
The full DPO loss is defined as:
Note that this DPO derivation assume the LLM inference as single-step MDP, the entier prompt and response are considered and , respectively. If we assume the process as multi-step MDP, we won’t be able to derive a DPO for the multi-step case (i.e. the partition function cannot be cancelled out in the Bradley-Terry formula).
<ins/>
3.5.3 DPO Code

From the final loss formula, this is essentially a kind of contrastive learning loss. It aims to maximize the probability gap between the preferred and less preferred responses (win/loss, chosen/reject).
The expected result is that the probability of the chosen answer increases, while the probability of the rejected answer decreases, thus achieving preference alignment with humans.
Of course, during training, it’s possible that both the chosen and reject probabilities decrease since DPO only constrains the difference between them. Later DPO variants introduce additional terms like NLL loss on the chosen answer or other regularization methods to optimize DPO.
PPO vs DPO
In theory, PPO has a higher performance upper bound because reinforcement learning includes an exploration process, which may allow it to discover better states not previously seen.
In contrast, DPO (offline DPO) is entirely limited to already labeled data. However, DPO is much more convenient to implement, while PPO requires many engineering tricks to work well, like training a good reward model, which is itself a technical challenge.
That's why many works are exploring combined approaches between DPO and PPO, such as Online DPO.
<ins/>
3.5.4 Understand DPO via Advantages
Previously, we acquired the below equation between the optimal reward and optimal policy
by solving
Similarly, we can also derive a relationship between the optimal advantages and optimal policy
by solving
Derivation
We aim to solve:
where is the advantage function, is a temperature parameter, and is a reference policy.
First, the KL divergence term expands as:
Let to be:
Then,
Set the derivative to zero for optimality, we get
Exponentiate both sides:
The optimal policy must satisfy , so we introduce a normalization factor
where . You can observe that this partition function also only depends on and , and does not depend on policy . Let’s cancel out the exponential part
Also,
QED.
Now, we can further derive the DPO by incorporating this into the Bradley-Terry model. If you remember there are six versions of returns mentioned in 3.2.10 Actor-Critic Algorithm, here we do similar things by substituting the return with advantages
You can observe this formula is exactly the same as we derived before by starting from return ! Therefore, we also have
You may be confused: if the final equation is the same, why bother?
This is because we are doing human preference alignment at the sentence level, which makes it a single-step MDP. But under multi-step MDP cases, you’ll see they are different.
For example, below is a simple grid world RL environment, where the agent receives a reward of -1 for each step and only gets a reward of 100 upon reaching the goal.
Now consider the two agent trajectories: path S (left) and path O (right). If we use the total reward as the metric to align with human preferences, then both trajectories have the same total reward:
So the preference model would treat them equally, but it's clear that path O should be preferred, because the agent is moving toward the goal, while in path S, the agent is moving away from it.
However, if we use advantage values as a preference metric, we can clearly predict that the cumulative advantage value in path O is larger, or in other words, the cumulative regret is smaller:
Actually, we could also use the action-value function , but advantage functions can be directly related to the optimal policy as we derived earlier.
<ins/>
3.5.5 Understand DPO via Contrast Learning
If we denote positive samples (preferred) and negative samples (not preferred) as , , the DPO loss can be written as:
Generally, the goal of contrastive learning is to learn a representation such that similar samples are close to each other, while dissimilar samples are far apart. For a query sample (e.g., a dog image), suppose we have a positive sample (e.g., another view of the same dog image after augmentation) and a set of negative samples (e.g., samples from some cat images). To learn an encoding function , contrastive learning typically minimizes the following loss:
By minimizing the loss , we are basically maximizing the and minimizing . Here, the dot product between representations (e.g., ) serves as the similarity score between two samples.
Therefore, you can observe that the input dog image is pulled away from negative cat images, while also pushing close to the positive augmented dog image.
DPO can be seen as contrastive learning where the input prompt can be viewed as the input dog image in the above case; the preferred answer is the augmented dog image; and the not preferred answer is seen as other cat images.
The similarity score of the dot-product is replaced by the output of the policy model, such as , where a higher score represents higher similarity. So we are expecting a higher similarity between input prompt and the preferred answer , such that the policy model can give higher possibilities to tokens belonging to the preferred answer , and give lower possibilities to tokens belonging to the not preferred answer .
The parts about , logarithmic, and the are just for regularization.
3.5.6 DPOP Algorithm
Motivation: The sampling probabilities for
chosen and rejected answers decrease at the same time, although the probability of the rejected answer decreases more than that of the chosen answer.Approach:
To address this, DPOP adds a regularization term on top of the DPO loss:
- If the current
chosenanswer’s sampling probability in the SFT reference model > the sampling probability in the current Policy model, minus a regularization factor (which means the current policy hasn’t been optimized well on thechosenanswer yet, so we give it a penalty, which increases the loss);
- If the
chosenanswer’s sampling probability in the Policy model is higher, it indicates that the Policy model has already fitted this chosen answer well; so, at this point, we don’t give the additional penalty.

<ins/>
3.5.7 TDPO Algorithm
The idea is to add token-level KL constraint

Let’s first focus on the , where the is formulated as
This is a token-level KL constraint. You may notice that the added green parts have the at the first position and at the second. This is
forward KL, which is different from the reverse KL used in PPO/DPO.Simply put, since KL is an asymmetric distance function,forwardandreverseunder this case essentially mean whetherthe sampling probability is calculated based on SFT reference modelorcalculated based on the Policy Model, respectively.
In the source code, we can see the calculation method of
forward KL:Why Token-level KL?
- Finer Granularity of Supervision:
Sequence-level KL is an aggregation over the entire sequence, making it difficult to precisely control the model's behavior at each token. Token-level KL can explicitly inform the model at which positions it deviates from the reference policy , thereby enabling step-by-step correction for each token.
- More Stable Training:
The fluctuation of token-level KL is usually smaller than sequence-level KL, which helps reduce variance.
Why forward KL?
- Problem with reverse KL (used in DPO):
Reverse KL is mode-seeking: it penalizes the policy heavily when it places mass outside the reference distribution. This leads to reduced diversity and overly conservative model behavior (i.e., sticking too closely to the reference model).
- Advantages of forward KL:
Forward KL is mass-covering: it encourages the policy to cover the support of the reference model more broadly. This results in a better diversity of generated responses.

The and are just two different versions, where the second one adds one more hyperparameter of so that the degree of impact of KL correction terms on losses can be flexibly controlled; and the indicates stop-gradient.
Using on the KL divergence of the winning example prevents its gradient from backpropagating; this indicates that we do not want the model to try to adjust the KL of the winning sample, but instead focus on improving the KL of the loser sample. This reduces training instability and improves robustness.
<ins/>
3.5.8 Self-Reward

Workflow:
- Initialization and Seed Data:
- First, a pre-trained base language model (e.g., Llama 2 70B) and a small amount of human-annotated seed data are needed.
- Seed data includes instruction fine-tuning (IFT) data and evaluation fine-tuning (EFT) data.
- Self-Instruction Creation:
- Use few-shot prompting to generate new instructions from the seed IFT data.
- The model generates multiple responses for the new instruction.
- The model uses an LLM-as-a-Judge mechanism to evaluate and score the quality of these responses, i.e., the model simulates the role of a reward model.
- Instruction Following Training:
- Construct preference pairs from the self-instructed data, consisting of the model-generated best and worst responses.
- Train the model using Direct Preference Optimization (DPO) to obtain the next-generation model .
- Iterative Training:
- This is an iterative process, where each round of training builds on the previous results.
- The model refines its ability to generate and evaluate responses more accurately through repeated iterations.
- This approach allows the model to break free from the limitations of fixed reward models in traditional training processes.
- Performance Evaluation:
- Model performance is evaluated from two dimensions: instruction-following and reward modeling.
- Instruction following is measured via comparing with other SOTA models and public leaderboard rankings (such as AlpacaEval 2.0).
- Reward modeling is measured using correlation with human preference, including exact match, Spearman correlation, and Kendall’s τ.
Experimental results show that both instruction following and reward modeling improve significantly through self-reward training. On the AlpacaEval 2.0 leaderboard, self-reward-based models show a clear win-rate boost.

- Compared to using IFT alone (i.e. the SFT baseline), adding EFT tasks into training (i.e. the self-rewarding method) does not affect the instruction-following ability (30.5% win rate vs. 30.9% win rate). This indicates that improving the model’s reward capability does not negatively impact other abilities.
- You can observe that with each iterative round, the performance steadily improves.
Prev
3.4 Optimizing PPO-Based Algorithms
Next
4.1 BERT & Variants
Loading...
