Neural Mastery
← Practice
Direct Preference Optimization (DPO) Lossmedium

Direct Preference Optimization (DPO) Loss

mediumLLMs & GenAI⏱ 15–20 min
Libraries allowed · Pure Python earns +10 bonus XP
🎯 Mission
Implement the Direct Preference Optimization (DPO) loss equation for aligning language models with human preferences.

Task

Implement `dpo_loss` calculating $-\log \sigma (\beta \log \frac{\pi_\theta(y_w)}{\pi_{ref}(y_w)} - \beta \log \frac{\pi_\theta(y_l)}{\pi_{ref}(y_l)})$.

Function Signature

dpo_loss(policy_chosen_logps: float, policy_rejected_logps: float, ref_chosen_logps: float, ref_rejected_logps: float, beta: float) -> float

Examples

Example 1: Zero Preference Margin
Input: {"policy_chosen_logps":-1,"policy_rejected_logps":-2,"ref_chosen_logps":-1,"ref_rejected_logps":-2,"beta":0.1}
Output: 0.6931471805599453

Constraints

  • Must compute log-ratios pi_logratio = policy_chosen - policy_rejected and ref_logratio = ref_chosen - ref_rejected.
  • logits = beta * (pi_logratio - ref_logratio).
  • Return -log(sigmoid(logits)).
Python3Saved ✓
def dpo_loss(policy_chosen_logps, policy_rejected_logps, ref_chosen_logps, ref_rejected_logps, beta=0.1):
"""
Computes DPO loss for a single sample or batch.
Return scalar loss float.
"""
# Your implementation here
pass

Case 1: Zero Preference Margin
Input: {"policy_chosen_logps":-1,"policy_rejected_logps":-2,"ref_chosen_logps":-1,"ref_rejected_logps":-2,"beta":0.1}
Expected: 0.6931471805599453