🤖 AI/ML

DPO

Direct Preference Optimization

A training method that directly optimizes preferences without a reward model. A simplified version of RLHF.

📖 Detailed Explanation

DPO (Direct Preference Optimization) is a training method that aligns large language models (LLMs) with human preferences. It simplifies the complex pipeline of conventional RLHF (Reinforcement Learning from Human Feedback) by optimizing the model directly on preference data, without a separate reward model.

DPO was introduced in the paper "Your Language Model is Secretly a Reward Model" by a Stanford research team (Rafael Rafailov et al.) in 2023. By reformulating the mathematical objective of RLHF, it proved that the same optimal solution can be found without reinforcement learning.

DPO uses a preference dataset (prompt, chosen, rejected). For each prompt, it trains to maximize the difference in log probability between the preferred response (chosen) and the dispreferred response (rejected). During this process, the KL divergence from the reference model constrains the model so that it does not drift too far from the original.

In practice, DPO trains more stably than RLHF, requires less hyperparameter tuning, and has lower compute cost. It is widely used for alignment of recent open-source LLMs such as Llama 2, Zephyr, and Mistral, and is easy to implement with the HuggingFace TRL library.

💻 Code Example

from transformers import AutoModelForCausalLM, AutoTokenizer
from trl import DPOTrainer, DPOConfig
from datasets import load_dataset

# 모델 및 토크나이저 로드
model_name = "meta-llama/Llama-2-7b-hf"
model = AutoModelForCausalLM.from_pretrained(model_name)
tokenizer = AutoTokenizer.from_pretrained(model_name)
tokenizer.pad_token = tokenizer.eos_token

# Reference 모델 (학습 중 고정)
ref_model = AutoModelForCausalLM.from_pretrained(model_name)

# DPO 데이터셋 로드 (prompt, chosen, rejected 컬럼 필요)
dataset = load_dataset("Anthropic/hh-rlhf", split="train[:1000]")

# DPO 학습 설정
training_args = DPOConfig(
    output_dir="./dpo-llama",
    per_device_train_batch_size=4,
    gradient_accumulation_steps=4,
    learning_rate=5e-7,  # DPO는 낮은 lr 권장
    beta=0.1,            # KL penalty 강도 (핵심 하이퍼파라미터)
    max_length=512,
    max_prompt_length=256,
    num_train_epochs=1,
    logging_steps=10,
    bf16=True,
)

# DPO Trainer 초기화 및 학습
trainer = DPOTrainer(
    model=model,
    ref_model=ref_model,
    args=training_args,
    train_dataset=dataset,
    tokenizer=tokenizer,
)

trainer.train()
trainer.save_model("./dpo-llama-final")

🗣️ Say It Like This in Practice

💬 In a Meeting
"Let's use DPO for this LLM alignment. It's simpler to implement than RLHF, and it doesn't have the instability problems of PPO training. We just need to build good preference data."
💬 In an Interview
"DPO combines RLHF's reward model and RL training into a single supervised loss. The beta parameter controls the KL divergence penalty, and you usually start somewhere between 0.1 and 0.5."
💬 In a Technical Discussion
"DPO is simple, but it's sensitive to the quality of the preference data. Performance drops sharply when there are many noisy labels, so you have to put real effort into data filtering. Variants like IPO and cDPO have also come out recently."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌
Applying DPO directly without SFT

Applying DPO directly to a base model degrades performance. First teach the basic response format with SFT (Supervised Fine-Tuning), then apply DPO.

❌
Using too high a learning rate

DPO requires a much lower lr (1e-7 to 5e-6) than ordinary fine-tuning. A high lr causes model collapse.

✅
The right pipeline

Proceed in the order SFT → DPO, start beta at 0.1 and adjust. Use the SFT checkpoint as the reference model, and secure at least 10,000 preference examples.

🔗 Related Terms

📚 Learn More