[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -1,67 +1,281 @@
|
||||
---
|
||||
id: wiki-2026-0508-dpo-direct-preference-optimizati
|
||||
id: wiki-2026-0508-dpo
|
||||
title: DPO (Direct Preference Optimization)
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-Reinforce-AUTO-DPOO-001]
|
||||
aliases: [DPO, ORPO, SimPO, IPO, KTO, preference learning, RLHF alternative, alignment]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.97
|
||||
tags: [auto-reinforced, dpo, direct-pReference-Optimization, llm-Alignment, Reinforcement-Learning, machine-learning]
|
||||
confidence_score: 0.95
|
||||
verification_status: applied
|
||||
tags: [llm, alignment, dpo, rlhf, preference-optimization, ppo, fine-tuning, trl]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-20
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
tech_stack:
|
||||
language: Python
|
||||
framework: TRL / DeepSpeed / Axolotl
|
||||
---
|
||||
|
||||
# [[DPO (Direct Preference Optimization)|DPO (Direct Preference Optimization)]]
|
||||
# DPO (Direct Preference Optimization)
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "복잡한 보상 모델은 가라: 인간의 선호도를 맞추기 위해 별도의 리워드 모델을 만들고 강화학습(PPO)을 돌리는 복잡한 과정 대신, 답변 쌍(Pair) 중 무엇이 좋은지 직접 알려줌으로써 모델을 한 번에 정렬하는 효율적인 혁신."
|
||||
## 매 한 줄
|
||||
> **"매 reward model 의 X — 매 preference pair 의 직접 학습"**. Rafailov et al. 2023. 매 RLHF 의 simpler + 매 stable + 매 effective alternative. 매 modern variant: ORPO, SimPO, KTO. 매 Llama-3, Tülu, 매 most open model 의 standard.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
직접 선호도 최적화(DPO, Direct Preference Optimization)는 LLM을 인간의 의도에 맞게 정렬하는 최신 기법입니다.
|
||||
## 매 핵심
|
||||
|
||||
1. **전통적 방식(RLHF/PPO)과의 차이**:
|
||||
* **RLHF**: 보상 모델 학습 -> 보상 모델을 이용한 강화학습(PPO)의 2단계로 매우 불안정하고 자원이 많이 듦.
|
||||
* **DPO**: 보상 모델 없이, "답변 A가 답변 B보다 낫다"는 선호도 데이터를 사용하여 모델의 로그 확률(Log probability)을 직접 조정.
|
||||
2. **장점**:
|
||||
* 수학적으로 더 단순하고 안정적임.
|
||||
* PPO와 같은 극도로 복잡한 강화학습 하이퍼파라미터 튜닝이 필요 없음.
|
||||
* 학습 속도가 빠르고 효과가 비슷하거나 더 뛰어남.
|
||||
### 매 vs RLHF
|
||||
| 측면 | RLHF (PPO) | DPO |
|
||||
|---|---|---|
|
||||
| Reward model | Required | None |
|
||||
| Stages | 2 (RM → PPO) | 1 |
|
||||
| Stability | Hard | Stable |
|
||||
| Hyperparameter | Many | Few |
|
||||
| Compute | High | Lower |
|
||||
| Quality | Strong | Comparable |
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌**: 과거에는 성공적인 정렬을 위해 반드시 '외부 보상 정책'이 필요하다고 믿었으나, 현대 정책은 모델의 자체 분포 정책만으로도 충분히 선호도를 학습할 수 있음을 입증함(RL Update).
|
||||
- **정책 변화(RL Update)**: DPO 이후 이를 개선한 ORPO, SimPO, IPO 등 '직접 최적화 파생 정책'들이 쏟아져 나오며, 데이터 효율을 극대화하고 모델의 거부(Refusal) 경향을 조절하는 정책이 정밀화됨.
|
||||
### 매 DPO loss
|
||||
$$L_{DPO} = -\log \sigma\left(\beta \log \frac{\pi_\theta(y_w|x)}{\pi_{ref}(y_w|x)} - \beta \log \frac{\pi_\theta(y_l|x)}{\pi_{ref}(y_l|x)}\right)$$
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- [[RLHF (인간 피드백 기반 강화 학습)|RLHF (인간 피드백 기반 강화 학습)]], [[Constitutional AI (헌법 AI)|Constitutional AI (헌법 AI)]], [[Alignment|Alignment]], [[Optimization|Optimization]], [[Policy-Optimization|Policy-Optimization]]
|
||||
- **Modern Tech/Tools**: TRL (Transformer Reinforcement Learning) library, Llama-3 alignment, Axolotl.
|
||||
---
|
||||
- 매 y_w = 매 winner (preferred).
|
||||
- 매 y_l = 매 loser.
|
||||
- 매 β = 매 KL coefficient.
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
### 매 derivation insight
|
||||
- 매 PPO objective 의 closed-form: 매 reward = 매 log-probability ratio.
|
||||
- 매 reward model 의 implicitly learned by 매 policy.
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
### 매 variant
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
#### ORPO (Odds Ratio PO)
|
||||
- 매 reference model 의 free.
|
||||
- 매 SFT + 매 preference 의 single stage.
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
#### SimPO (Simple PO)
|
||||
- 매 reference 의 free.
|
||||
- 매 length-normalize.
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
#### IPO (Identity PO)
|
||||
- 매 DPO 의 deterministic preference 의 fix.
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
#### KTO (Kahneman-Tversky Optimization)
|
||||
- 매 binary feedback (good / bad) — 매 pair 없이.
|
||||
- 매 prospect theory inspired.
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
#### SLiC-HF
|
||||
- 매 sequence-level contrastive.
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
#### CPO (Contrastive PO)
|
||||
- 매 reference-free + length-aware.
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
### 매 data
|
||||
- **HH-RLHF** (Anthropic): 매 helpful + harmless.
|
||||
- **UltraFeedback**.
|
||||
- **Nectar**.
|
||||
- **PKU-Beaver**.
|
||||
- **Tülu**.
|
||||
|
||||
### 매 modern stack
|
||||
- **TRL** (HuggingFace): 매 DPOTrainer, ORPOTrainer.
|
||||
- **Axolotl**: 매 config-driven.
|
||||
- **DeepSpeed**.
|
||||
- **Unsloth**: 매 fast LoRA.
|
||||
|
||||
### 매 응용
|
||||
1. **LLM alignment**: 매 helpful + harmless.
|
||||
2. **Fine-tune on preference**: 매 customer service tone.
|
||||
3. **Code style**: 매 specific convention.
|
||||
4. **Refusal calibration**: 매 over-refusal 의 reduce.
|
||||
|
||||
### 매 limitation
|
||||
- 매 reference model 의 quality 의 critical.
|
||||
- 매 length bias (longer 의 win 의 tend).
|
||||
- 매 over-conservative (mode-seeking).
|
||||
- 매 verifier-based (RLVR) 가 매 specific 의 better.
|
||||
|
||||
## 💻 패턴
|
||||
|
||||
### DPOTrainer (TRL)
|
||||
```python
|
||||
from trl import DPOTrainer, DPOConfig
|
||||
from transformers import AutoModelForCausalLM, AutoTokenizer
|
||||
from datasets import load_dataset
|
||||
|
||||
model = AutoModelForCausalLM.from_pretrained('mistralai/Mistral-7B-v0.1')
|
||||
ref_model = AutoModelForCausalLM.from_pretrained('mistralai/Mistral-7B-v0.1')
|
||||
tokenizer = AutoTokenizer.from_pretrained('mistralai/Mistral-7B-v0.1')
|
||||
|
||||
# 매 dataset format: {prompt, chosen, rejected}
|
||||
dataset = load_dataset('trl-lib/ultrafeedback_binarized')
|
||||
|
||||
config = DPOConfig(
|
||||
output_dir='./dpo-mistral',
|
||||
per_device_train_batch_size=4,
|
||||
gradient_accumulation_steps=4,
|
||||
learning_rate=5e-7,
|
||||
num_train_epochs=1,
|
||||
beta=0.1, # 매 KL coefficient
|
||||
max_length=2048,
|
||||
max_prompt_length=512,
|
||||
)
|
||||
|
||||
trainer = DPOTrainer(
|
||||
model=model,
|
||||
ref_model=ref_model,
|
||||
args=config,
|
||||
train_dataset=dataset['train'],
|
||||
tokenizer=tokenizer,
|
||||
)
|
||||
trainer.train()
|
||||
```
|
||||
|
||||
### Manual DPO loss
|
||||
```python
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
|
||||
def dpo_loss(policy_logp_chosen, policy_logp_rejected,
|
||||
ref_logp_chosen, ref_logp_rejected, beta=0.1):
|
||||
pi_logratio = policy_logp_chosen - policy_logp_rejected
|
||||
ref_logratio = ref_logp_chosen - ref_logp_rejected
|
||||
return -F.logsigmoid(beta * (pi_logratio - ref_logratio)).mean()
|
||||
|
||||
# 매 logp = log P(y | x)
|
||||
```
|
||||
|
||||
### ORPO (no reference)
|
||||
```python
|
||||
from trl import ORPOTrainer, ORPOConfig
|
||||
|
||||
config = ORPOConfig(
|
||||
output_dir='./orpo-mistral',
|
||||
learning_rate=8e-6,
|
||||
beta=0.1, # 매 odds ratio coefficient
|
||||
)
|
||||
|
||||
# 매 매 SFT + preference 의 single stage
|
||||
trainer = ORPOTrainer(model=model, args=config, train_dataset=dataset, tokenizer=tokenizer)
|
||||
trainer.train()
|
||||
```
|
||||
|
||||
### KTO (binary feedback)
|
||||
```python
|
||||
from trl import KTOTrainer, KTOConfig
|
||||
|
||||
# 매 dataset format: {prompt, completion, label: True / False}
|
||||
config = KTOConfig(
|
||||
output_dir='./kto',
|
||||
beta=0.1,
|
||||
desirable_weight=1.0,
|
||||
undesirable_weight=1.0,
|
||||
)
|
||||
|
||||
trainer = KTOTrainer(model=model, ref_model=ref_model, args=config, train_dataset=dataset)
|
||||
trainer.train()
|
||||
```
|
||||
|
||||
### LoRA + DPO (efficient)
|
||||
```python
|
||||
from peft import LoraConfig
|
||||
|
||||
peft_config = LoraConfig(
|
||||
r=16, lora_alpha=32,
|
||||
target_modules=['q_proj', 'k_proj', 'v_proj', 'o_proj'],
|
||||
lora_dropout=0.05,
|
||||
task_type='CAUSAL_LM',
|
||||
)
|
||||
|
||||
config = DPOConfig(...)
|
||||
|
||||
trainer = DPOTrainer(
|
||||
model=model,
|
||||
args=config,
|
||||
train_dataset=dataset,
|
||||
tokenizer=tokenizer,
|
||||
peft_config=peft_config, # 매 LoRA
|
||||
)
|
||||
```
|
||||
|
||||
### Preference data generation (synthetic)
|
||||
```python
|
||||
def generate_preference_pair(prompt, model_a, model_b, judge):
|
||||
response_a = model_a.generate(prompt)
|
||||
response_b = model_b.generate(prompt)
|
||||
|
||||
chosen, rejected = judge(prompt, response_a, response_b)
|
||||
return {'prompt': prompt, 'chosen': chosen, 'rejected': rejected}
|
||||
|
||||
# 매 LLM-as-judge
|
||||
def gpt4_judge(prompt, a, b):
|
||||
judgment = gpt4.generate(f"""Which response is better?
|
||||
Prompt: {prompt}
|
||||
A: {a}
|
||||
B: {b}
|
||||
|
||||
Reply: A or B""")
|
||||
return (a, b) if 'A' in judgment else (b, a)
|
||||
```
|
||||
|
||||
### Length bias mitigation
|
||||
```python
|
||||
# 매 SimPO: 매 length-normalized
|
||||
def simpo_loss(logp_chosen, logp_rejected, len_chosen, len_rejected, beta=0.5, gamma=1.0):
|
||||
pi_chosen = logp_chosen / len_chosen # 매 normalize
|
||||
pi_rejected = logp_rejected / len_rejected
|
||||
return -F.logsigmoid(beta * (pi_chosen - pi_rejected) - gamma).mean()
|
||||
```
|
||||
|
||||
### Eval (preference accuracy)
|
||||
```python
|
||||
def eval_preference_accuracy(model, eval_set):
|
||||
correct = 0
|
||||
for ex in eval_set:
|
||||
logp_chosen = model.compute_logp(ex['chosen'])
|
||||
logp_rejected = model.compute_logp(ex['rejected'])
|
||||
if logp_chosen > logp_rejected: correct += 1
|
||||
return correct / len(eval_set)
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Method |
|
||||
|---|---|
|
||||
| Standard alignment | DPO |
|
||||
| Single-stage | ORPO |
|
||||
| Length-sensitive | SimPO |
|
||||
| Binary feedback | KTO |
|
||||
| Verifiable reward | RLHF (PPO) or RLVR |
|
||||
| Limited compute | DPO + LoRA |
|
||||
| Open dataset | UltraFeedback / HH-RLHF |
|
||||
| Tone fine-tune | DPO + custom pairs |
|
||||
|
||||
**기본값**: DPO + LoRA (efficient) + UltraFeedback.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[LLM-Alignment]] · [[Fine-Tuning]] · [[Preference-Learning]]
|
||||
- 변형: [[ORPO]] · [[SimPO]] · [[KTO]] · [[IPO]] · [[CPO]]
|
||||
- 응용: [[TRL]] · [[Axolotl]] · [[Unsloth]] · [[Llama]]
|
||||
- Adjacent: [[RLHF]] · [[Constitutional-AI]] · [[Best-of-N_Sampling]] · [[Credit Assignment Problem]] · [[Cross-Entropy Loss]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 LLM alignment. 매 customer-specific tone. 매 RLHF alternative. 매 fine-tune at scale.
|
||||
**언제 X**: 매 verifiable task (RLVR / process reward). 매 small data (SFT 의 enough).
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **No reference model** (DPO): 매 over-fit.
|
||||
- **β too high**: 매 underutilize preference.
|
||||
- **β too low**: 매 reference 의 drift.
|
||||
- **Length bias 의 ignore**: 매 long answer 의 win.
|
||||
- **Single-pair training**: 매 noisy.
|
||||
- **No SFT first**: 매 quality drop.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Rafailov et al. 2023 DPO, ORPO 2024, KTO 2024).
|
||||
- 신뢰도 A.
|
||||
- Related: [[RLHF]] · [[Constitutional-AI]] · [[Best-of-N_Sampling]] · [[Credit Assignment Problem]] · [[Cross-Entropy Loss]].
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — DPO formula + variants + 매 TRL / ORPO / KTO / LoRA / SimPO code |
|
||||
|
||||
Reference in New Issue
Block a user