Direct Preference Optimization

DPO turns pairwise preferences into binary cross-entropy on reference-relative log odds, using the KL-regularized RLHF optimum to make the policy itself an implicit reward model.

published · difficulty 4/5 · 18 min read

Reading map and next steps

Intuition

Build the mental picture first so the rest of the page has something to attach to.

PredictName the object in plain language, then predict what should change.Leave with one reusable mental picture before notation appears.

Suppose a prompt xx has two candidate completions:

  • ywy_w: the preferred completion
  • yℓy_\ell: the rejected completion

RLHF usually trains a reward model rϕ(x,y)r_\phi(x,y), then runs an RL algorithm to make the policy choose higher-reward outputs while staying close to a reference model.

DPO asks a sharper question: can the policy itself act as the reward model?

Under the KL-regularized RLHF objective, the answer is yes, but only up to a prompt-only constant. If a policy has moved away from the reference model, that movement gives a convenient representative of an implicit reward class:

r^θ(x,y)=βlog⁡πθ(y∣x)πref(y∣x).\hat r_\theta(x,y) = \beta\log \frac{\pi_\theta(y\mid x)} {\pi_{\mathrm{ref}}(y\mid x)}.

The exact reward can differ from this representative by a term that depends only on xx. Only reward differences matter for preference pairs, so that prompt-only term cancels, and DPO compares how much the current policy has changed the winner-vs-loser odds relative to the reference policy.

The core idea is:

A preferred response should beat a rejected response by more than the reference model already made it beat it.

That "more than the reference" phrase is the whole mechanism. DPO is not just "make the winner more likely." It is binary cross-entropy on reference-relative log odds.

Section prompt

Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.

Math

Translate the story into symbols, assumptions, and a derivation you can inspect.

InspectTrack the same object through the notation and check each symbol.Leave with the invariant the equations preserve.

The source-level representative is the beta-scaled policy/reference log-ratio:

r^θ(x,y)=βlog⁡πθ(y∣x)πref(y∣x).\hat r_\theta(x,y) = \beta\log\frac{\pi_\theta(y\mid x)}{\pi_{\mathrm{ref}}(y\mid x)}.

Setup and shapes

For a prompt xx, πθ(y∣x)\pi_\theta(y\mid x) is the full sequence probability of completion yy. In an autoregressive language model,

log⁡πθ(y∣x)=∑tlog⁡πθ(yt∣x,y<t).\log \pi_\theta(y\mid x) = \sum_t \log \pi_\theta(y_t\mid x,y_{<t}).

A preference datum is (x,yw,yℓ)(x,y_w,y_\ell). All compared completions must have positive probability under the reference policy for the log ratio to be finite.

Define the policy and reference log-odds:

aθ=log⁡πθ(yw∣x)−log⁡πθ(yℓ∣x),a_\theta = \log\pi_\theta(y_w\mid x) - \log\pi_\theta(y_\ell\mid x),

and

aref=log⁡πref(yw∣x)−log⁡πref(yℓ∣x).a_{\mathrm{ref}} = \log\pi_{\mathrm{ref}}(y_w\mid x) - \log\pi_{\mathrm{ref}}(y_\ell\mid x).

The reference-relative margin is

mθ=aθ−aref.m_\theta=a_\theta-a_{\mathrm{ref}}.

DPO predicts the preference probability as

Pθ(yw≻yℓ∣x)=σ(βmθ).P_\theta(y_w\succ y_\ell\mid x) = \sigma(\beta m_\theta).

For one hard winner/loser label, the DPO loss is

LDPO=−log⁡σ(βmθ).\mathcal L_{\mathrm{DPO}} = -\log\sigma(\beta m_\theta).

Let sθ=σ(βmθ)s_\theta=\sigma(\beta m_\theta). The browser demo below uses a soft target p∗p^* so the finite target log-odds is visible:

Lsoft=−p∗log⁡sθ−(1−p∗)log⁡(1−sθ).\mathcal L_{\mathrm{soft}} = -p^*\log s_\theta -(1-p^*)\log(1-s_\theta).

Ordinary hard-label DPO is the edge case p∗→1p^*\to 1, where an isolated two-response target diverges.

From KL-regularized RLHF to DPO

For a fixed prompt xx, write Kx(π)K_x(\pi) for the distribution-level KL from a candidate policy to the reference policy at that prompt. The direction is π(⋅∣x)\pi(\cdot\mid x) to πref(⋅∣x)\pi_{\mathrm{ref}}(\cdot\mid x):

Kx(π)=KLx(π∥πref).K_x(\pi) = \mathrm{KL}_x(\pi\|\pi_{\mathrm{ref}}).

Also write the expected reward as

Rx(π)=Ey∼π(⋅∣x)[r(x,y)].R_x(\pi) = \mathbb E_{y\sim\pi(\cdot\mid x)}[r(x,y)].

The KL-regularized RLHF objective is to maximize

Jx(π)=Rx(π)−βKx(π).J_x(\pi) = R_x(\pi)-\beta K_x(\pi).

Its optimizer has the reweighted form

πr(y∣x)=πref(y∣x)exp⁡(r(x,y)/β)Z(x).\pi_r(y\mid x) = \frac{\pi_{\mathrm{ref}}(y\mid x)\exp(r(x,y)/\beta)} {Z(x)}.

Rearrange it:

r(x,y)=βlog⁡πr(y∣x)πref(y∣x)+βlog⁡Z(x).r(x,y) = \beta\log \frac{\pi_r(y\mid x)} {\pi_{\mathrm{ref}}(y\mid x)} + \beta\log Z(x).

The partition term Z(x)Z(x) depends on the prompt, not on which completion won. Bradley-Terry preferences use reward differences, so the prompt-only term cancels between ywy_w and yℓy_\ell.

Bradley-Terry likelihood

Bradley-Terry models a preference as

P(yw≻yℓ∣x)=σ(r(x,yw)−r(x,yℓ)).P(y_w\succ y_\ell\mid x) = \sigma(r(x,y_w)-r(x,y_\ell)).

Substituting the implicit reward gives the DPO probability. With the margin mθ=aθ−arefm_\theta=a_\theta-a_{\mathrm{ref}} from above:

Pθ(yw≻yℓ∣x)=σ(βmθ).P_\theta(y_w\succ y_\ell\mid x) =\sigma(\beta m_\theta).

Maximum likelihood on preference labels gives the DPO loss. This is why DPO is a supervised objective even though it comes from a KL-regularized RLHF derivation.

What beta does

Here β\beta follows the DPO paper's convention: it is the coefficient on the KL penalty in the KL-regularized RLHF objective.

  • Larger β\beta means a stronger reference anchor in the underlying RLHF objective.
  • Smaller β\beta means a given preference probability requires a larger policy/reference log-ratio gap.
  • In the DPO loss, β\beta also scales the sigmoid margin, so it affects optimization dynamics. Do not read "larger β\beta" as simply "trust preferences more."

For a soft preference probability p∗p^*, matching p∗p^* requires

m∗=logit⁡(p∗)β.m^*=\frac{\operatorname{logit}(p^*)}{\beta}.

Limits of the mechanism

DPO removes the explicit reward-model training stage and the RL loop. It does not remove the assumptions behind preference learning.

It still relies on a pairwise preference model such as Bradley-Terry. It only identifies rewards up to prompt-dependent constants. It needs a usable reference policy. And in an isolated two-response hard-label setting, the logistic loss can keep increasing the winner-over-loser log-ratio rather than settling at a finite target.

Section prompt

Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.

Code

Keep the implementation aligned with the notation so the algorithm is legible.

TraceMatch variables to symbols before reading the implementation.Leave with a runnable witness for the math.

This finite-action witness verifies the derivation directly in a clean realizable toy setting. A synthetic reward defines the KL-regularized target policy. DPO sees full-support, exact soft Bradley-Terry preference probabilities and recovers the same unconstrained categorical policy through reference-relative log-ratio cross-entropy. Sampled hard labels, missing pairs, or a restricted neural parameterization would not make the equality exact in finite data.

import numpy as np

def softmax(z):
    z = z - z.max()
    e = np.exp(z)
    return e / e.sum()

def sigmoid(x):
    return 1.0 / (1.0 + np.exp(-x))

def kl(p, q):
    return float(np.sum(p * (np.log(p) - np.log(q))))

# One prompt, three possible completions.
# Shapes: ref, reward, logits, pi are all (K,).
ref = np.array([0.15, 0.70, 0.15], dtype=float)
reward = np.array([1.0, 0.2, -0.5], dtype=float)
beta = 0.5
log_ref = np.log(ref)

# KL-regularized RLHF optimum:
# pi*(y|x) is proportional to pi_ref(y|x) exp(r(x,y)/beta).
pi_star = ref * np.exp(reward / beta)
pi_star = pi_star / pi_star.sum()

# DPO sees pairwise preferences. We use exact Bradley-Terry
# probabilities instead of sampled hard labels so the equality is visible.
pairs = [(0, 1), (0, 2), (1, 2)]

# Initialize policy at the reference.
logits = log_ref.copy()
lr = 0.2

for _ in range(3000):
    grad = np.zeros_like(logits)

    for i, j in pairs:
        rel_log_odds = (logits[i] - logits[j]) - (log_ref[i] - log_ref[j])
        pred = sigmoid(beta * rel_log_odds)

        target = sigmoid(reward[i] - reward[j])

        # Binary cross-entropy gradient for the soft preference target.
        g = beta * (pred - target)
        grad[i] += g
        grad[j] -= g

    logits -= lr * grad / len(pairs)
    logits -= logits.mean()  # logits are identifiable only up to a constant

pi = softmax(logits)

print("reference policy:      ", np.round(ref, 3))
print("KL-reg optimum:        ", np.round(pi_star, 3))
print("DPO learned policy:    ", np.round(pi, 3))
print("KL(pi || ref):         ", round(kl(pi, ref), 4))

assert np.allclose(pi, pi_star, atol=1e-6)

for i, j in pairs:
    implicit_gap = beta * (
        (np.log(pi[i]) - np.log(ref[i]))
        - (np.log(pi[j]) - np.log(ref[j]))
    )
    reward_gap = reward[i] - reward[j]
    assert abs(implicit_gap - reward_gap) < 1e-6

for i, j in pairs:
    dpo_pref = sigmoid(beta * (
        (np.log(pi[i]) - np.log(ref[i]))
        - (np.log(pi[j]) - np.log(ref[j]))
    ))
    bt_pref = sigmoid(reward[i] - reward[j])
    assert abs(dpo_pref - bt_pref) < 1e-6
Section prompt

Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.

Interactive Demo

Use direct manipulation to connect the explanation to a moving system.

ManipulateChange one control and predict the visible response before reveal.Leave with the observed invariant or a repaired model.

Live Concept Demo

Explore Direct Preference Optimization

The stage is code-native and interactive. Use it to test the explanation against the mechanism.

difficulty 4/5undergraduatecode-aligned
Demo inquiry checkpoint

Manipulate one control and predict the visible change.

01Choose lensTrace a quantity
02ObserveDemo state pending
03GroundName the equation, invariant, or control that explains it.
04CarryNext: Kahneman-Tversky Optimization

Choose what to inspect in Direct Preference Optimization. This shared fallback is an observation guide, not evidence of learning.

Loading interactive demo...

Use the demo as a ratio machine. It collapses the world to two completions, ywy_w and yℓy_\ell, so its KL is the binary KL over this toy pair, not the full language-model KL over all completions. Change the reference winner probability, the soft target preference, and β\beta. Watch how the required policy log-odds moves relative to the reference, how the DPO probability changes, and when the two-action KL from the reference spikes.

Section prompt

Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.

4/4 sections ready

Concept: Direct Preference Optimization

What is the smallest example that makes Direct Preference Optimization click without losing the math?

BeforeCross-EntropyNow4/4 sections readyTryManipulate one control and predict the visible change.NextKahneman-Tversky Optimization
Object contextAlignment
ConceptLearner lens

Direct Preference Optimization

What is the smallest example that makes Direct Preference Optimization click without losing the math?

Mode questionCan I say the mechanism back in one sentence before I reveal anything?

Start with the prediction checkpoint, then compare the reveal to the mental model.

Take this move

Study modes

Keep the object fixed; change the lens.

Route back through the notebook

Carry the same object through intuition, math, code, and demo.

4/4 sections ready
Carry inCross-Entropy

Bring the mental model from Cross-Entropy; this page will reuse it instead of restarting from zero.

Work hereDirect Preference Optimization

DPO turns pairwise preferences into binary cross-entropy on reference-relative log odds, using the KL-regularized RLHF optimum to make the policy itself an implicit reward model.

Carry outKahneman-Tversky Optimization

The next edge should feel earned: use the demo prediction here before following Kahneman-Tversky Optimization.

After The First Pass

Turn the concept into an inspected object.

The lower panels are one second act: keep the object fixed, inspect it visually, check source boundaries, practice transfer, then attach the research question.
ConceptDirect Preference OptimizationAlignment

Mechanism Storyboard

See the idea move before the page explains it

DPO turns pairwise preferences into binary cross-entropy on reference-relative log odds, using the KL-regularized RLHF optimum to make the policy itself an implicit reward model.

Demo notes open01 / Intuition
Editorial alignment illustration of a direct preference comparison tilting chosen and rejected probability paths.
Prediction lens

Start with the picture, metaphor, or geometric mechanism.

Commit first

Before reading further, choose the kind of change Direct Preference Optimization should make visible.

Visual Inquiry

Make the image answer a mathematical question

DPO turns pairwise preferences into binary cross-entropy on reference-relative log odds, using the KL-regularized RLHF optimum to make the policy itself an implicit reward model.

4/4 stages readyDemo notes connected
Prediction

Which visible object should carry the first intuition?

Commit first

Pick the cue that should make Direct Preference Optimization easier to reason about before the page gives the answer.

Source Grounding

Canonical references for the mechanism on this page.

Object - ConceptDirect Preference OptimizationQuestion

What is the smallest example that makes Direct Preference Optimization click without losing the math?

concept:alignment/dpo
Boundary

sources: rafailov-2023-dpo

Check

Open the closest source note before trusting the local explanation.

Evidence

1 selected-object source shown first; 1 reference total.

Next move

Audit the claim boundary, then ask from the same selected object.

selected object source · paper · 2023Direct Preference Optimization: Your Language Model is Secretly a Reward ModelRafailov et al.
Located CF editorial boundary

Grounds DPO as a closed-form preference objective derived from KL-regularized RLHF.

Used here as

Rafailov et al. derive the KL-regularized optimum pi_r proportional to pi_ref exp(r/beta), rearrange it as r=beta log(pi_r/pi_ref)+beta log Z(x), then substitute into Bradley-Terry pairwi...

Caveat

Checks pairwise Bradley-Terry DPO derivation plus finite-action/two-completion intuition only; not finite-sample convergence, noisy hard labels, neural realizability, ranking variants, em...

Open source

Claim Review

DPO turns pairwise preferences into binary cross-entropy on reference-relative log odds, using the KL-regularized RLHF optimum to make the policy itself an implicit reward model.

Object - ConceptDirect Preference OptimizationQuestion

What is the smallest example that makes Direct Preference Optimization click without losing the math?

concept:alignment/dpo
Boundary

sources: rafailov-2023-dpo

Check

Treat every claim as provisional until source support and a local witness agree.

Evidence

1 structured claim check on this concept.

Next move

Run the prediction or practice transfer before asking for a grounded review.

1 CF editorial source-scope review recorded

Publisher-side editorial review is not independent replication. Claims without it still need exact source-support review. 1 reference and 3 local witnesses are available for inspection.

DPO reparameterizes the KL-regularized RLHF reward as beta times the policy/reference log-ratio, up to a prompt-only constant, then fits preference pairs with binary cross-entropy on the beta-scaled winner-loser reference-relative log-odds margin.
Used here as

Rafailov et al. derive the KL-regularized optimum pi_r proportional to pi_ref exp(r/beta), rearrange it as r=beta log(pi_r/pi_ref)+beta log Z(x), then substitute into Bradley-Terry pairwise preferences so Z(...

Local witness
Equation 1
r^θ(x,y)=βlog⁡πθ(y∣x)πref(y∣x).\hat r_\theta(x,y) = \beta\log\frac{\pi_\theta(y\mid x)}{\pi_{\mathrm{ref}}(y\mid x)}.
Caveat

Checks pairwise Bradley-Terry DPO derivation plus finite-action/two-completion intuition only; not finite-sample convergence, noisy hard labels, neural realizability, ranking variants, empirical superiority...

Review stateCF editorial source-scope reviewClaim metadata: source checkedPublisher-side editorial review only; not independent replication. Check caveats and exact source scope.

Rafailov et al. derive pi_r proportional to pi_ref exp(r/beta), rearrange r=beta log(pi_r/pi_ref)+beta log Z(x), then cancel Z(x) in Bradley-Terry reward differences to obtain DPO BCE/logistic loss on beta-scaled policy-vs-reference winner-loser log-odds.

Reviewer: codex+oracle; reviewed 2026-05-07

Practice · Direct Preference Optimization

Try the idea in your own words

DPO turns pairwise preferences into binary cross-entropy on reference-relative log odds, using the KL-regularized RLHF optimum to make the policy itself an implicit reward model.

Concept · Current object

Direct Preference Optimization

Source boundary: sources: rafailov-2023-dpo

Object context and links
Choose a task

Explain the mechanism

For Direct Preference Optimization: What is the smallest example that makes Direct Preference Optimization click without losing the math? Explain your answer, including what changes, why, and which assumption matters.

No answer yet

A rough first thought is enough. Your draft stays when you change tasks.

Local to this page session. Not saved after leaving or reloading.

A little help · Explain

Open one hint at a time. These are suggestions, not your answer or a grade.

0 of 3 hints shown for this question.

    Clearing your answer does not erase help history. Outside help cannot be verified here.

    Where am I stuck? (optional)
    Your own description, not an automatic diagnosis

    Choose one, or leave this unspecified. Select it again to clear it.

    Take your draft to a feedback conversation

    No AI feedback runs here. You can copy a prompt to use elsewhere; nothing is sent automatically. Review the text before sharing, and leave out private information.

    Write an attempt before copying a feedback prompt.

    This draft and any AI response do not establish mastery. Try a different case later without help; this page has not measured that learning.

    Grounded object roomClose
    Selected object routeAsk from this object; carry one invariant back.sources: rafailov-2023-dpo
    1. ObjectConceptDirect Preference Optimization
    2. PredictBefore revealDirect Preference Optimization prediction
    3. WitnessCompare codeDirect Preference Optimization code witness 1
    4. RoomAsk groundedChecking local snapshot
    ConceptDirect Preference OptimizationAlignment

    Research Room

    Attach the question to an exact object

    Pick the concept, equation, source, code witness, claim, misconception, or demo state before asking for help. The handoff stays grounded to that object.
    Next local actionNo local draft saved yet

    Open the draft below to save one note and next action in this browser.

    conceptAlignment

    Direct Preference Optimization

    Anchored question

    What is the smallest example that makes Direct Preference Optimization click without losing the math?

    Source boundaryInspect source ids: rafailov-2023-dpoStable content-object key attached
    Role lenses for this object

    These are fixed, deterministic perspectives derived from the selected object. They do not represent people, community contributions, or independent review.

    Learner evidence requestAsk what would make "Direct Preference Optimization" feel predictable rather than familiar.
    Assumption

    Source ids rafailov-2023-dpo must support the exact object, not just the surrounding topic.

    Source-checking summary

    Treat this as a mechanism object: connect the definition to one equation, code witness, or demo before broadening the discussion.

    Proposed experiment

    Ask the learner to perturb one representation, then check whether the same invariant survives in math, code, and demo.

    Next action

    The learner can state the mechanism in their own words

    Evidence4 checks
    PredictionChecking carried observation
    ActionReady for one action
    AILearner handoff ready
    Open source object
    01PredictionChecking browser-local route memory
    02EvidenceChecking for a carried observation
    03BoundaryInspect source ids: rafailov-2023-dpo
    04Next moveSave one next action
    Local action draftNo local draft saved yetExpand only when ready to capture one local next action
    Local action draft

    This draft stays locally in this browser for concept:alignment/dpo.

    No local draft saved.
    Evidence to inspect
    • Source ids to inspect: rafailov-2023-dpo
    • Definition, prerequisite, and contrast concept links
    • The equation or code witness that makes the concept operational
    • One demo state that shows the invariant instead of a slogan
    What would resolve this
    • The learner can state the mechanism in their own words
    • The learner can name the prerequisite that would repair confusion
    • The learner can predict how the mechanism changes under one perturbation
    Object-attached AI handoff

    I am working in Continuous Function's research reading room. Object: concept - Direct Preference Optimization Object key: concept:alignment/dpo Context: Alignment Anchor id: concept/concept-notebook/alignment/dpo Open question: What is the smallest example that makes Direct Preference Optimization click without losing the math? Evidence to inspect: - Source ids to inspect: rafailov-2023-dpo - Definition, prerequisite, and contrast concept links - The equation or code witness that makes the concept operational - One demo state that shows the invariant instead of a slogan Deterministic role lenses for this object: - Boundary: fixed perspectives, not people, community contributions, or independent review - Source-checking summary: Treat this as a mechanism object: connect the definition to one equation, code witness, or demo before broadening the discussion. - Proposed experiment: Ask the learner to perturb one representation, then check whether the same invariant survives in math, code, and demo. - Teach/transfer move: Turn the mechanism into one sentence that predicts a neighboring concept. - Assumptions: - Source ids rafailov-2023-dpo must support the exact object, not just the surrounding topic. - The stable content-object key lets local drafts, prompts, and route memory attach without changing the source page. - The concept explanation is local atlas prose until checked against its math, code, and source support. - Prerequisite gaps should become a repair route, not a reason to leave the object vague. - Role-lens requests: - Learner: ask for "Ask what would make "Direct Preference Optimization" feel predictable rather than familiar." | assumption: Source ids rafailov-2023-dpo must support the exact object, not just the surrounding topic. | next action: The learner can state the mechanism in their own words - Researcher: ask for "Source ids to inspect: rafailov-2023-dpo" | assumption: The stable content-object key lets local drafts, prompts, and route memory attach without changing the source page. | next action: The learner can name the prerequisite that would repair confusion - Experimenter: ask for "Choose one variable or condition to perturb before asking for an explanation." | assumption: The concept explanation is local atlas prose until checked against its math, code, and source support. | next action: The learner can predict how the mechanism changes under one perturbation - Professor: ask for "Find the smallest transferable rule a learner could reuse without the AI." | assumption: Prerequisite gaps should become a repair route, not a reason to leave the object vague. | next action: Teach or transfer: Turn the mechanism into one sentence that predicts a neighboring concept. What would resolve this: - The learner can state the mechanism in their own words - The learner can name the prerequisite that would repair confusion - The learner can predict how the mechanism changes under one perturbation Answer as a careful research tutor: stay source-grounded, separate verified evidence from assumptions, name the relevant math objects, and end with one next action. Current deterministic role lens for this object: - Role lens: Learner - Evidence request: Ask what would make "Direct Preference Optimization" feel predictable rather than familiar. - Assumption to keep visible: Source ids rafailov-2023-dpo must support the exact object, not just the surrounding topic. - Proposed experiment: Ask the learner to perturb one representation, then check whether the same invariant survives in math, code, and demo. - Next action: The learner can state the mechanism in their own words

    concept/concept-notebook/alignment/dpo concept:alignment/dpo