In Lesson 3 we saw that the optimum of the KL-regularised objective is . That equation expresses the policy in terms of the reward. Read backwards, it expresses the reward in terms of the policy. And the reward model is trained with the Bradley–Terry loss. Put these two facts together and you get a loss that learns a policy directly from preference pairs — no reward model, no sampling, no RL loop. This is DPO (Direct Preference Optimization), and methods of this family are called direct alignment algorithms (DAA).
Derivation: the partition function disappears
Take the log of the closed-form solution and solve for :
is still intractable. But the Bradley–Terry model involves only the reward difference between two responses to the same prompt (Lesson 2). Take the difference and cancels.
Now replace with the policy to be trained, , and minimise the negative log-likelihood of the preference data.
Here is how to read it. The policy by itself defines a reward model (the implicit reward), and DPO fits this implicit reward with the BT loss. And the KL-regularised optimal policy for that reward is itself. The moment you fit the reward model, you already hold its optimal policy.
It also matters that this parameterisation loses nothing. Rewards and give the same optimal policy and cannot be told apart by BT either (Lesson 2). Each such equivalence class has exactly one representative that can be written as , so searching in policy space and searching in reward space are the same problem (assuming the policy class is expressive enough).
Gradient: more weight on pairs it gets wrong
Writing and ,
It raises the log-prob of the chosen response and lowers that of the rejected one, weighting each pair by how wrongly the implicit reward orders it. This is the role played in the RM gradient of Lesson 2. The DPO paper reported that simply increasing without this weight makes the model degenerate. The weight stops learning on pairs that are already far enough apart; that is how the KL regularisation survives inside the loss.
레슨 3에서 KL 정규화 목적함수의 최적해가 라는 것을 보았다. 이 식은 정책을 보상으로 표현한다. 거꾸로 읽으면 보상을 정책으로 표현할 수 있다. 그리고 보상모델은 Bradley–Terry 손실로 학습한다. 이 두 사실을 붙이면 보상모델도, 샘플링도, RL 루프도 없이 선호 쌍에서 바로 정책을 학습하는 손실이 나온다. 이것이 DPO(Direct Preference Optimization) 이고, 같은 계열의 방법들을 direct alignment algorithms(DAA) 라고 부른다.
유도: 분배함수가 사라진다
닫힌 해 에 로그를 취해 에 대해 풀면
는 여전히 계산할 수 없다. 하지만 Bradley–Terry 모델에는 같은 prompt의 두 응답의 보상 차이만 들어간다(레슨 2). 차이를 취하면 가 상쇄된다.
이제 자리에 학습할 정책 를 넣고, 선호 데이터의 음의 로그우도를 최소화한다.
읽는 법은 이렇다. 정책 는 그 자체로 보상모델 를 정의하고(implicit reward), DPO는 이 implicit reward를 BT 손실로 학습한다. 그리고 그 보상에 대한 KL 정규화 최적 정책은 자신이다. 보상모델을 맞추는 순간 그 최적 정책이 이미 손에 있는 것이다.
이 parameterization이 손해를 보지 않는다는 점도 중요하다. 보상 과 는 같은 최적 정책을 주고 BT로 구분도 안 된다(레슨 2). 이 동치류마다 꼴로 쓸 수 있는 대표가 정확히 하나 있으므로, 정책 공간에서 찾는 것과 보상 공간에서 찾는 것은 같은 문제다(정책 클래스가 충분히 표현력 있다는 가정 아래).
Gradient: 틀린 쌍에 더 큰 무게
, 라 쓰면
chosen의 log-prob은 올리고 rejected의 log-prob은 내리는데, 쌍마다 implicit reward가 순서를 틀린 정도만큼 무게를 준다. 레슨 2의 RM gradient에서 가 하던 역할과 같다. DPO 논문은 이 가중치 없이 단순히 을 키우면 모델이 퇴화한다고 보고했다. 가중치가 이미 충분히 벌어진 쌍에서 학습을 멈추게 해 주는 것이 KL 정규화가 손실 안에 남아 있는 방식이다.
- Put the point on the diagonal (Δw = Δl): the loss is and the weight is 0.5. The starting point of training () is the origin.
- The arrow direction is the same everywhere. In log-ratio space it is always “raise chosen and lower rejected by the same amount”. How each log-prob actually moves depends on parameter sharing (see the toy experiment below).
- Even in the lower-left quadrant, the loss is small if Δw > Δl. The loss does nothing to stop the chosen probability from falling.
- Lower β to 0.01: the colour gradient in the left panel becomes gentler and the weight curve on the right spreads out. To get the same drop in loss, the log-ratio has to open up further, so a small β lets the policy move further from . It means the same thing as β in RLHF. The default in implementations such as TRL is 0.1.
Implementation: tabular DPO vs the closed-form solution
Consider a single prompt with only 6 responses. The labeller produces BT preferences from a hidden reward , and response pairs are drawn from . We check whether the policy trained by DPO matches from Lesson 3.
import numpy as np
rng = np.random.default_rng(0)
def softmax(z):
e = np.exp(z - z.max()); return e / e.sum()
sigmoid = lambda z: 1 / (1 + np.exp(-z))
K, beta = 6, 0.5
pi_ref = softmax(np.array([1.0, 0.6, 0.3, 0.0, -0.4, -0.8]))
r_true = np.array([0.0, 1.0, -0.5, 1.6, 0.4, -1.0]) # labeller's hidden reward
pi_star = pi_ref * np.exp(r_true / beta); pi_star /= pi_star.sum() # closed-form solution from Lesson 3
def dpo_grad(theta, C):
"""DPO loss and gradient for a tabular policy π_θ = softmax(θ).
C[w, l] = number of (y_w=w, y_l=l) pairs in the data (identical pairs grouped for speed)."""
logp = np.log(softmax(theta)); logp_ref = np.log(pi_ref)
h = beta * (logp - logp_ref) # implicit reward r_θ(y) = β log π_θ/π_ref
M = h[:, None] - h[None, :] # M[w, l] = r_θ(y_w) - r_θ(y_l)
n = C.sum()
loss = -(C * np.log(sigmoid(M))).sum() / n
wgt = C * sigmoid(-M) # the more wrongly ordered the pair, the larger the weight
# ∇_θ [log π(y_w) - log π(y_l)] = onehot(y_w) - onehot(y_l) (the softmax normaliser cancels)
g = -beta * (wgt.sum(1) - wgt.sum(0)) / n
return loss, g
def ipo_grad(theta, C, tau=0.5):
"""IPO: squared loss regressing the log-ratio difference onto 1/(2τ)."""
h = np.log(softmax(theta)) - np.log(pi_ref)
resid = (h[:, None] - h[None, :]) - 1 / (2 * tau)
n = C.sum()
wgt = C * 2 * resid
return (C * resid ** 2).sum() / n, (wgt.sum(1) - wgt.sum(0)) / n
def train(C, grad_fn=dpo_grad, steps=3000, lr=2.0):
theta = np.log(pi_ref).copy() # start π_θ at π_ref
for _ in range(steps):
loss, g = grad_fn(theta, C)
theta -= lr * g
return softmax(theta), loss
def sample_prefs(n, deterministic=False):
a = rng.choice(K, n, p=pi_ref); b = rng.choice(K, n, p=pi_ref) # two responses from π_ref
a, b = a[a != b], b[a != b]
p_a = sigmoid(r_true[a] - r_true[b]) # Bradley–Terry
a_wins = (p_a > 0.5) if deterministic else (rng.random(len(a)) < p_a)
C = np.zeros((K, K))
np.add.at(C, (np.where(a_wins, a, b), np.where(a_wins, b, a)), 1)
return C
tv = lambda p, q: 0.5 * np.abs(p - q).sum()
print("π_ref :", np.round(pi_ref, 3))
print("π* (analytic):", np.round(pi_star, 3))
for n in [200, 20_000]:
pi_dpo, _ = train(sample_prefs(n))
print(f"DPO n={n:<6}:", np.round(pi_dpo, 3), f" TV(π_dpo, π*)={tv(pi_dpo, pi_star):.3f}")
C_det = sample_prefs(20_000, deterministic=True)
pi_det, loss = train(C_det)
r_hat = beta * np.log(pi_det / pi_ref)
print("\nDPO, deterministic labels:", np.round(pi_det, 3), f" loss={loss:.3f}")
print(f" implicit reward range {r_hat.max() - r_hat.min():.1f} vs true reward range {r_true.max() - r_true.min():.1f}")
pi_ipo, _ = train(C_det, ipo_grad, lr=0.2)
h = np.log(pi_ipo / pi_ref)
print("IPO, deterministic labels:", np.round(pi_ipo, 3), f" log-ratio range {h.max() - h.min():.2f} (finite, set by τ)")With enough BT labels the DPO policy converges to (the TV distance shrinks with more data). With deterministic labels (always picking the response with larger true reward) the story changes. To fit on every pair, the implicit reward difference has to be infinite, so DPO piles all the mass onto one response regardless of β. The KL regularisation effectively vanishes. This is why Azar et al. proposed IPO. IPO regresses the log-ratio difference onto a fixed target instead of infinity, so the policy stays at a finite distance.
Failure modes
1. Chosen and rejected fall together. This is often seen in DPO training logs. The margin (the difference) grows, but the chosen log-prob also ends up lower than at the start. Lambert’s book calls this preference (likelihood) displacement and describes probability leaking out to other behaviours that were not in the data. Because the loss looks only at the difference, nothing prevents it, and the cause is parameter sharing. See it for yourself in the figure below.
- 점을 대각선(Δw = Δl) 위에 두면 손실은 , 가중치는 0.5다. 학습 시작점()이 원점이다.
- 화살표 방향은 어디서나 같다. 로그-비율 공간에서는 언제나 “chosen을 올리고 rejected를 같은 만큼 내린다”이다. 실제로 각 log-prob이 어떻게 움직이는지는 파라미터 공유에 달려 있다(아래 장난감 실험).
- 왼쪽 아래 사분면에서도 Δw > Δl이면 손실이 작다. 손실은 chosen 확률이 떨어지는 것을 막지 않는다.
- β = 0.01로 내리면 왼쪽 그림의 색 변화가 완만해지고 오른쪽 가중치 곡선이 넓게 퍼진다. 같은 손실 감소를 얻으려면 log-ratio가 더 크게 벌어져야 하므로, 작은 β는 정책이 에서 더 멀리 움직이는 것을 허용한다. RLHF의 β와 같은 의미다. TRL 등 구현의 기본값은 0.1이다.
구현: 표 형태 DPO와 닫힌 해 비교
응답이 6개뿐인 prompt 하나를 생각하자. 라벨러는 숨은 보상 로 BT 선호를 만들고, 응답 쌍은 에서 뽑는다. DPO로 학습한 정책이 레슨 3의 와 같아지는지 본다.
import numpy as np
rng = np.random.default_rng(0)
def softmax(z):
e = np.exp(z - z.max()); return e / e.sum()
sigmoid = lambda z: 1 / (1 + np.exp(-z))
K, beta = 6, 0.5
pi_ref = softmax(np.array([1.0, 0.6, 0.3, 0.0, -0.4, -0.8]))
r_true = np.array([0.0, 1.0, -0.5, 1.6, 0.4, -1.0]) # 라벨러의 숨은 보상
pi_star = pi_ref * np.exp(r_true / beta); pi_star /= pi_star.sum() # 레슨 3의 닫힌 해
def dpo_grad(theta, C):
"""표 형태(tabular) 정책 π_θ = softmax(θ) 에 대한 DPO 손실과 gradient.
C[w, l] = 데이터에서 (y_w=w, y_l=l) 쌍이 나온 횟수 (같은 쌍을 묶어서 빠르게 계산)."""
logp = np.log(softmax(theta)); logp_ref = np.log(pi_ref)
h = beta * (logp - logp_ref) # implicit reward r_θ(y) = β log π_θ/π_ref
M = h[:, None] - h[None, :] # M[w, l] = r_θ(y_w) - r_θ(y_l)
n = C.sum()
loss = -(C * np.log(sigmoid(M))).sum() / n
wgt = C * sigmoid(-M) # 틀리게 정렬된 쌍일수록 가중치가 크다
# ∇_θ [log π(y_w) - log π(y_l)] = onehot(y_w) - onehot(y_l) (softmax 정규화 항은 상쇄)
g = -beta * (wgt.sum(1) - wgt.sum(0)) / n
return loss, g
def ipo_grad(theta, C, tau=0.5):
"""IPO: 로그-비율 차이를 1/(2τ)로 회귀하는 제곱 손실."""
h = np.log(softmax(theta)) - np.log(pi_ref)
resid = (h[:, None] - h[None, :]) - 1 / (2 * tau)
n = C.sum()
wgt = C * 2 * resid
return (C * resid ** 2).sum() / n, (wgt.sum(1) - wgt.sum(0)) / n
def train(C, grad_fn=dpo_grad, steps=3000, lr=2.0):
theta = np.log(pi_ref).copy() # π_θ 를 π_ref 에서 시작
for _ in range(steps):
loss, g = grad_fn(theta, C)
theta -= lr * g
return softmax(theta), loss
def sample_prefs(n, deterministic=False):
a = rng.choice(K, n, p=pi_ref); b = rng.choice(K, n, p=pi_ref) # π_ref 에서 두 응답
a, b = a[a != b], b[a != b]
p_a = sigmoid(r_true[a] - r_true[b]) # Bradley–Terry
a_wins = (p_a > 0.5) if deterministic else (rng.random(len(a)) < p_a)
C = np.zeros((K, K))
np.add.at(C, (np.where(a_wins, a, b), np.where(a_wins, b, a)), 1)
return C
tv = lambda p, q: 0.5 * np.abs(p - q).sum()
print("π_ref :", np.round(pi_ref, 3))
print("π* (해석해) :", np.round(pi_star, 3))
for n in [200, 20_000]:
pi_dpo, _ = train(sample_prefs(n))
print(f"DPO n={n:<6}:", np.round(pi_dpo, 3), f" TV(π_dpo, π*)={tv(pi_dpo, pi_star):.3f}")
C_det = sample_prefs(20_000, deterministic=True)
pi_det, loss = train(C_det)
r_hat = beta * np.log(pi_det / pi_ref)
print("\n결정적 라벨 DPO:", np.round(pi_det, 3), f" loss={loss:.3f}")
print(f" implicit reward 폭 {r_hat.max() - r_hat.min():.1f} vs 진짜 보상 폭 {r_true.max() - r_true.min():.1f}")
pi_ipo, _ = train(C_det, ipo_grad, lr=0.2)
h = np.log(pi_ipo / pi_ref)
print("결정적 라벨 IPO:", np.round(pi_ipo, 3), f" 로그-비율 폭 {h.max() - h.min():.2f} (τ가 정하는 유한한 값)")BT 라벨이 충분하면 DPO 정책은 에 수렴한다(TV 거리가 데이터와 함께 줄어든다). 라벨이 결정적이면(항상 진짜 보상이 큰 쪽을 고름) 이야기가 달라진다. 모든 쌍에서 을 맞추려면 implicit reward 차이가 무한대여야 하므로, DPO는 β와 상관없이 질량을 한 응답에 몰아넣는다. KL 정규화가 사실상 사라진다. 이것이 Azar et al.이 IPO를 제안한 이유다. IPO는 로그-비율 차이를 무한대가 아니라 고정된 목표 로 회귀시키므로 정책이 유한한 거리에 머문다.
실패 모드
1. chosen과 rejected가 함께 떨어진다. DPO 학습 로그에서 자주 보는 현상이다. 마진(차이)은 커지는데 chosen의 log-prob도 처음보다 낮아진다. Lambert의 책은 이것을 preference(likelihood) displacement라 부르고, 확률이 데이터에 없던 다른 행동으로 새어 나간다고 정리한다. 손실이 차이만 보기 때문에 막을 장치가 없고, 원인은 파라미터 공유다. 아래 그림에서 직접 보자.
For a tabular policy the gradient raises only the chosen logit and lowers only the rejected logit, so with a single pair the chosen probability must go up. But when responses share representations (as they obviously do in a real LLM), the direction that pushes down the rejected response also pushes down similar chosen ones. Razin et al. (2024) showed that the more similar the hidden representations of chosen and rejected, the worse this gets, and proposed filtering out such pairs. There are also variants such as DPO-Positive (Pal et al. 2024) that add a penalty when the chosen probability falls below .
# 6 responses (A..F), each with a 2-D embedding h_y. Policy logit = z_ref + h_y · θ (θ is only 2-D: parameter sharing)
H = np.array([[1.0, 0.2], [1.1, 0.5], [0.9, 0.6], [0.2, 1.0], [-0.6, -0.4], [-1.0, 0.3]])
z_ref = np.array([0.4, 0.6, 0.2, 0.0, -0.3, -0.5])
lp_ref = np.log(softmax(z_ref))
pairs = [(0, 1), (0, 2)] # A ≻ B, A ≻ C
b_toy = 0.5
def run(shared, steps=200, lr=1.0):
theta = np.zeros(2 if shared else 6)
logits = (lambda th: z_ref + H @ th) if shared else (lambda th: z_ref + th)
for t in range(steps + 1):
lp = np.log(softmax(logits(theta)))
if t % 50 == 0:
ch = lp[0] - lp_ref[0]
rj = np.mean([lp[1] - lp_ref[1], lp[2] - lp_ref[2]])
print(f" step {t:3d}: Δlog π(A) {ch:+.3f} Δlog π(B,C) {rj:+.3f} margin {ch - rj:+.3f} π(E)={np.exp(lp[4]):.3f}")
g = np.zeros_like(theta)
for w, l in pairs:
m = b_toy * ((lp[w] - lp_ref[w]) - (lp[l] - lp_ref[l]))
s = sigmoid(-m) # DPO weight
# ∇θ[log π(w) − log π(l)] = ∂z_w/∂θ − ∂z_l/∂θ
g += b_toy * s * ((H[w] - H[l]) if shared else (np.eye(6)[w] - np.eye(6)[l]))
theta += lr * g / len(pairs)
print("Tabular (independent logit per response)"); run(shared=False)
print("Shared representation (2-D embeddings)"); run(shared=True)With shared representations, while the margin grows steadily, A’s log-prob drops below its starting value and probability piles onto E, which never appears in the data. That is because the embedding differences and both point towards E. In a real LLM, “E” might be a strange format, a different language, or excessive verbosity.
2. Length exploitation. Both humans and LLM judges tend to prefer longer responses, so in preference data the chosen response is longer on average. DPO uses the sum of log-probs over the whole sequence, so length and implicit reward get entangled easily, and responses getting longer after training has been reported (Park et al. 2024). Length normalisation (SimPO, Tülu 3’s length-normalised DPO) or a length penalty are the remedies.
3. Off-policy data. DPO data are usually responses produced by other models. The policy gets no feedback on the responses it actually produces, and responses that gives high probability but that are not in the data (E above) are not constrained at all. In RLHF the RM keeps scoring the policy’s own samples, so it finds and fills such holes by itself (or exploits them). That is why modern recipes build preference pairs from responses sampled from the policy (on-policy preference data).
During DPO training, the log-probs of both chosen and rejected are falling, while their difference (the margin) is growing. What is the most accurate interpretation?
The DPO loss is a function of , so even if and both go negative, the loss falls as long as the difference grows. In a real model with shared parameters, the gradient pushing down the rejected response also pushes down similar chosen ones, and the mass that leaves goes to responses outside the data (likelihood displacement). That might be better generalisation or a strange output. So you must evaluate actual generations alongside the chosen and rejected log-prob trends.
Variants
| Method | One-line summary |
|---|---|
| cDPO | Label smoothing that assumes a fixed fraction of labels is flipped: . The margin does not grow without bound. |
| IPO (Azar et al. 2023) | Instead of the BT log-likelihood, a squared loss regressing the log-ratio difference onto . KL regularisation survives even with deterministic preferences. |
| KTO (Ethayarajh et al. 2024) | Instead of pairs, a binary “good/bad” label per response. It evaluates the implicit reward relative to a reference point (a KL estimate) with a prospect-theory value function. Used for data where pairs are hard to build. |
| SimPO (Meng et al. 2024) | No reference model; uses the length-averaged log-prob as the reward, with a target margin . Reduces both memory and length bias. |
| ORPO (Hong et al. 2024) | No reference model; adds an odds ratio term between chosen and rejected to the SFT NLL, merging SFT and preference learning into one stage. |
| Online / iterative DPO | Sample responses from the current policy, label them with an RM or LLM judge, and repeat DPO. Reduces the off-policy problem and moves closer to RLHF. Llama 3’s multi-round DPO and Tülu 3’s on-policy preference data go in this direction. |
Every variant is a different answer to two questions: how to define the implicit reward (log-ratio against a reference model, length-normalised average log-prob, odds), and which loss fits that reward (BT log-likelihood, squared loss, a value function on binary labels).
import torch
import torch.nn.functional as F
def sequence_logps(model, input_ids, attention_mask, loss_mask):
"""loss_mask: 1 on response tokens, 0 on prompt and padding. Returns: (B,) sum of response-token log-probs."""
logits = model(input_ids=input_ids, attention_mask=attention_mask).logits # (B, T, V)
logits, labels, mask = logits[:, :-1], input_ids[:, 1:], loss_mask[:, 1:] # position t predicts token t+1
logp = torch.gather(logits.float().log_softmax(-1), 2, labels.unsqueeze(-1)).squeeze(-1)
return (logp * mask).sum(-1)
def dpo_loss(pol_w, pol_l, ref_w, ref_l, beta=0.1, label_smoothing=0.0):
"""pol_*/ref_*: sequence log-probs (B,) of chosen (w) and rejected (l)."""
r_w = beta * (pol_w - ref_w) # implicit reward
r_l = beta * (pol_l - ref_l)
h = r_w - r_l
loss = -(1 - label_smoothing) * F.logsigmoid(h) - label_smoothing * F.logsigmoid(-h) # ε>0 gives cDPO
stats = {"reward_acc": (h > 0).float().mean(), "margin": h.mean(),
"chosen_logp": pol_w.mean(), "rejected_logp": pol_l.mean()} # watch whether both go down
return loss.mean(), {k: v.detach() for k, v in stats.items()}
def train_step(policy, ref, batch, optimizer, beta=0.1):
ids = torch.cat([batch["chosen_ids"], batch["rejected_ids"]]) # in a single forward pass
att = torch.cat([batch["chosen_att"], batch["rejected_att"]])
lm = torch.cat([batch["chosen_loss_mask"], batch["rejected_loss_mask"]])
B = batch["chosen_ids"].size(0)
pol = sequence_logps(policy, ids, att, lm)
with torch.no_grad():
refl = sequence_logps(ref, ids, att, lm) # can be precomputed and cached
loss, stats = dpo_loss(pol[:B], pol[B:], refl[:B], refl[B:], beta)
optimizer.zero_grad(); loss.backward(); optimizer.step()
return loss.item(), statsIn the DPO gradient, what does the per-pair weight σ(r_θ(y_l) − r_θ(y_w)) do?
is the probability that the current implicit reward model gets the pair wrong. Pairs it already gets right by a large margin have a weight near 0 and stop pushing the policy. This is the trace of the KL regularisation left inside the loss (the smaller β, the further the policy has to go before the weight shrinks). The weight does not prevent the chosen probability from falling, and has no direct relation to length.
DPO vs PPO
After DPO appeared, a debate followed over whether RL is really necessary. Controlled comparisons mostly point the same way. Ivison et al. (2024) compared DPO and PPO on the same preference data and reported that well-tuned PPO is generally better than DPO, but that the quality of the preference data affects results more than that gap. Xu et al. (2024, “Is DPO Superior to PPO for LLM Alignment?”) also reported that a properly implemented PPO beats DPO on several tasks.
Summary
- DPO solves the expression for for the reward and substitutes it into BT so that cancels: .
- The policy is the reward model: . The gradient weights wrongly ordered pairs by .
- With enough BT data it reaches the same as RLHF, but with deterministic preferences the KL regularisation vanishes (IPO and cDPO address this).
- Because the loss looks only at the difference of log-ratios, chosen and rejected can fall together (parameter sharing → likelihood displacement). Length exploitation and off-policy data are other major failure modes.
- Variants change the definition of the implicit reward and the loss that fits it (IPO, KTO, SimPO, ORPO). Online/iterative DPO moves towards RLHF. At the frontier, online RL generally comes out ahead, but data quality matters more than the algorithm.
표 형태 정책에서는 gradient가 chosen의 logit만 올리고 rejected의 logit만 내리므로, 쌍이 하나면 chosen의 확률이 반드시 오른다. 하지만 응답들이 표현을 공유하면(실제 LLM은 당연히 그렇다) rejected를 누르는 방향이 비슷한 chosen까지 함께 누른다. Razin et al.(2024)은 chosen과 rejected의 hidden 표현이 비슷할수록 이 현상이 심하다는 것을 보이고, 그런 쌍을 걸러 내는 방법을 제안했다. Pal et al.(2024)의 DPO-Positive처럼 chosen의 확률이 아래로 떨어지면 벌점을 주는 변형도 있다.
# 응답 6개(A..F), 각자 2-D 임베딩 h_y. 정책 logit = z_ref + h_y · θ (θ 는 2차원뿐: 파라미터 공유)
H = np.array([[1.0, 0.2], [1.1, 0.5], [0.9, 0.6], [0.2, 1.0], [-0.6, -0.4], [-1.0, 0.3]])
z_ref = np.array([0.4, 0.6, 0.2, 0.0, -0.3, -0.5])
lp_ref = np.log(softmax(z_ref))
pairs = [(0, 1), (0, 2)] # A ≻ B, A ≻ C
b_toy = 0.5
def run(shared, steps=200, lr=1.0):
theta = np.zeros(2 if shared else 6)
logits = (lambda th: z_ref + H @ th) if shared else (lambda th: z_ref + th)
for t in range(steps + 1):
lp = np.log(softmax(logits(theta)))
if t % 50 == 0:
ch = lp[0] - lp_ref[0]
rj = np.mean([lp[1] - lp_ref[1], lp[2] - lp_ref[2]])
print(f" step {t:3d}: Δlog π(A) {ch:+.3f} Δlog π(B,C) {rj:+.3f} 마진 {ch - rj:+.3f} π(E)={np.exp(lp[4]):.3f}")
g = np.zeros_like(theta)
for w, l in pairs:
m = b_toy * ((lp[w] - lp_ref[w]) - (lp[l] - lp_ref[l]))
s = sigmoid(-m) # DPO 가중치
# ∇θ[log π(w) − log π(l)] = ∂z_w/∂θ − ∂z_l/∂θ
g += b_toy * s * ((H[w] - H[l]) if shared else (np.eye(6)[w] - np.eye(6)[l]))
theta += lr * g / len(pairs)
print("표 형태 (응답마다 독립 logit)"); run(shared=False)
print("공유 표현 (2-D 임베딩)"); run(shared=True)공유 표현에서는 마진이 꾸준히 커지는 동안 A의 log-prob이 처음보다 떨어지고, 데이터에 한 번도 나오지 않은 E로 확률이 몰린다. A와 B, C의 임베딩 차이 , 가 모두 E 쪽을 가리키기 때문이다. 실제 LLM에서 “E”는 이상한 형식, 다른 언어, 지나친 장황함일 수 있다.
2. 길이 착취. 사람과 LLM judge 모두 긴 응답을 선호하는 경향이 있어서, 선호 데이터에서는 chosen이 평균적으로 더 길다. DPO는 시퀀스 전체 log-prob의 합을 쓰므로 길이와 implicit reward가 쉽게 엮이고, 학습 후 응답이 길어지는 현상이 보고되었다(Park et al. 2024). 길이 정규화(SimPO, Tülu 3의 길이 정규화 DPO)나 길이 벌점이 대응책이다.
3. Off-policy 데이터. DPO의 데이터는 보통 다른 모델들이 만든 응답이다. 정책은 자기가 실제로 내는 응답에 대한 피드백을 받지 못하고, 가 높은 확률을 주지만 데이터에 없는 응답(위의 E)은 아무 제약을 받지 않는다. RLHF는 정책의 샘플을 RM이 계속 채점하므로 이런 구멍을 스스로 찾아 메운다(또는 착취한다). 그래서 현대 레시피는 정책에서 뽑은 응답으로 선호 쌍을 만든다(on-policy 선호 데이터).
DPO 학습 중 chosen과 rejected의 log-prob이 둘 다 내려가고, 둘의 차이(마진)는 커지고 있다. 가장 정확한 해석은?
DPO 손실은 의 함수라서 와 이 함께 음수가 되어도 차이가 커지면 손실은 줄어든다. 파라미터를 공유하는 실제 모델에서는 rejected를 누르는 gradient가 비슷한 chosen도 누르고, 빠져나간 질량은 데이터 밖의 응답으로 간다(likelihood displacement). 그 응답이 더 나은 일반화일 수도, 이상한 출력일 수도 있다. 그래서 chosen·rejected log-prob 추이와 함께 실제 생성물을 평가해야 한다.
변형들
| 방법 | 한 줄 요약 |
|---|---|
| cDPO | 라벨의 일정 비율이 뒤집혀 있다고 가정하는 label smoothing: . 마진이 무한히 커지지 않는다. |
| IPO (Azar et al. 2023) | BT의 로그우도 대신 로그-비율 차이를 로 회귀하는 제곱 손실. 결정적 선호에서도 KL 정규화가 유지된다. |
| KTO (Ethayarajh et al. 2024) | 쌍 대신 응답마다 “좋음/나쁨” 이진 라벨. 전망 이론(prospect theory)의 가치 함수로 implicit reward를 기준점(KL 추정치) 대비 평가한다. 쌍을 만들기 어려운 데이터에 쓴다. |
| SimPO (Meng et al. 2024) | 기준 모델 없이 길이로 나눈 평균 log-prob 를 보상으로 쓰고 목표 마진 를 둔다. 메모리와 길이 편향을 동시에 줄인다. |
| ORPO (Hong et al. 2024) | 기준 모델 없이 SFT의 NLL에 chosen과 rejected의 odds ratio 항을 더해, SFT와 선호 학습을 한 단계로 합친다. |
| Online / iterative DPO | 현재 정책에서 응답을 뽑고 RM이나 LLM judge로 라벨을 붙여 DPO를 반복한다. off-policy 문제를 줄이며 RLHF에 가까워진다. Llama 3의 여러 라운드 DPO, Tülu 3의 on-policy 선호 데이터가 이 방향이다. |
모든 변형은 결국 두 질문에 대한 다른 답이다. implicit reward를 무엇으로 정의하나(기준 모델 대비 log-ratio, 길이 정규화 평균 log-prob, odds), 그리고 그 보상을 어떤 손실로 맞추나(BT 로그우도, 제곱 손실, 이진 라벨의 가치 함수).
import torch
import torch.nn.functional as F
def sequence_logps(model, input_ids, attention_mask, loss_mask):
"""loss_mask: 응답 토큰 1, prompt·padding 0. 반환: (B,) 응답 토큰 log-prob의 합."""
logits = model(input_ids=input_ids, attention_mask=attention_mask).logits # (B, T, V)
logits, labels, mask = logits[:, :-1], input_ids[:, 1:], loss_mask[:, 1:] # 위치 t가 토큰 t+1을 예측
logp = torch.gather(logits.float().log_softmax(-1), 2, labels.unsqueeze(-1)).squeeze(-1)
return (logp * mask).sum(-1)
def dpo_loss(pol_w, pol_l, ref_w, ref_l, beta=0.1, label_smoothing=0.0):
"""pol_*/ref_*: chosen(w)·rejected(l)의 시퀀스 log-prob (B,)."""
r_w = beta * (pol_w - ref_w) # implicit reward
r_l = beta * (pol_l - ref_l)
h = r_w - r_l
loss = -(1 - label_smoothing) * F.logsigmoid(h) - label_smoothing * F.logsigmoid(-h) # ε>0 이면 cDPO
stats = {"reward_acc": (h > 0).float().mean(), "margin": h.mean(),
"chosen_logp": pol_w.mean(), "rejected_logp": pol_l.mean()} # 둘 다 내려가는지 감시
return loss.mean(), {k: v.detach() for k, v in stats.items()}
def train_step(policy, ref, batch, optimizer, beta=0.1):
ids = torch.cat([batch["chosen_ids"], batch["rejected_ids"]]) # 한 번의 forward로
att = torch.cat([batch["chosen_att"], batch["rejected_att"]])
lm = torch.cat([batch["chosen_loss_mask"], batch["rejected_loss_mask"]])
B = batch["chosen_ids"].size(0)
pol = sequence_logps(policy, ids, att, lm)
with torch.no_grad():
refl = sequence_logps(ref, ids, att, lm) # 미리 계산해 캐시해도 된다
loss, stats = dpo_loss(pol[:B], pol[B:], refl[:B], refl[B:], beta)
optimizer.zero_grad(); loss.backward(); optimizer.step()
return loss.item(), statsDPO의 gradient에서 쌍마다 곱해지는 가중치 σ(r_θ(y_l) − r_θ(y_w))가 하는 일은?
는 현재 implicit reward 모델이 그 쌍을 틀릴 확률이다. 이미 큰 마진으로 맞히는 쌍은 가중치가 0에 가까워 정책을 더 밀지 않는다. 이것이 손실 안에 남은 KL 정규화의 흔적이다(β가 작을수록 더 멀리 가야 가중치가 줄어든다). 가중치는 chosen 확률의 하락을 막지 않으며 길이와도 직접 관계가 없다.
DPO vs PPO
DPO가 나온 뒤 “RL이 정말 필요한가”라는 논쟁이 이어졌다. 통제된 비교들은 대체로 같은 방향을 가리킨다. Ivison et al.(2024)은 같은 선호 데이터로 DPO와 PPO를 비교해, 잘 튜닝한 PPO가 DPO보다 대체로 낫지만 그 차이보다 선호 데이터의 품질이 결과에 더 큰 영향을 준다고 보고했다. Xu et al.(2024, “Is DPO Superior to PPO for LLM Alignment?”)도 제대로 구현한 PPO가 여러 과제에서 DPO를 앞선다고 보고했다.
정리
- DPO는 의 식을 보상에 대해 풀고 BT에 대입해 를 상쇄시킨 것이다: .
- 정책이 곧 보상모델이다: . gradient는 순서를 틀린 쌍에 만큼 무게를 준다.
- 충분한 BT 데이터에서는 RLHF와 같은 에 가지만, 결정적 선호에서는 KL 정규화가 사라진다(IPO·cDPO가 대응).
- 손실이 log-ratio의 차이만 보므로 chosen·rejected가 함께 떨어질 수 있다(파라미터 공유 → likelihood displacement). 길이 착취와 off-policy 데이터도 주요 실패 모드다.
- 변형은 implicit reward의 정의와 맞추는 손실을 바꾼다(IPO, KTO, SimPO, ORPO). online/iterative DPO는 RLHF 쪽으로 다가간다. 프런티어에서는 online RL이 대체로 앞서지만, 데이터 품질이 알고리즘보다 중요하다.
더 읽을거리Further reading
- Rafailov et al., Direct Preference Optimization: Your Language Model is Secretly a Reward Model (NeurIPS 2023) — DPO 원 논문. 유도와 gradient 해석이 명료하다.The original DPO paper. The derivation and the interpretation of the gradient are clear.
- Lambert, RLHF Book, Ch. 8 Direct Alignment Algorithms (rlhfbook.com) — 유도, 변형 목록, preference displacement, DPO vs RL에 대한 저자의 견해.Derivation, a list of variants, preference displacement, and the author's view on DPO vs RL.
- Azar et al., A General Theoretical Paradigm to Understand Learning from Human Preferences (AISTATS 2024) — ΨPO 틀과 IPO. 결정적 선호에서 DPO가 KL 정규화를 잃는 이유.The ΨPO framework and IPO. Why DPO loses its KL regularisation under deterministic preferences.
- Ethayarajh et al., KTO: Model Alignment as Prospect Theoretic Optimization (ICML 2024) — 쌍이 아닌 좋음/나쁨 이진 라벨로 하는 정렬.Alignment with binary good/bad labels instead of pairs.
- Meng, Xia & Chen, SimPO: Simple Preference Optimization with a Reference-Free Reward (NeurIPS 2024) — 길이 정규화된 평균 log-prob을 보상으로, 기준 모델 없이.Uses the length-normalised average log-prob as the reward, without a reference model.
- Hong, Lee & Thorne, ORPO: Monolithic Preference Optimization without Reference Model (EMNLP 2024) — SFT 손실에 odds ratio 항을 더해 한 단계로.Adds an odds-ratio term to the SFT loss to do it in a single stage.
- Razin et al., Unintentional Unalignment: Likelihood Displacement in Direct Preference Optimization (2024) — chosen 확률까지 떨어지는 현상을 임베딩 유사도로 설명.Explains the drop in even the chosen probability through embedding similarity.
- Ivison et al., Unpacking DPO and PPO: Disentangling Best Practices for Learning from Preference Feedback (NeurIPS 2024) — 같은 데이터에서 DPO와 PPO를 통제 비교. 데이터 품질이 가장 큰 요인.A controlled comparison of DPO and PPO on the same data. Data quality is the biggest factor.