00:00:00

Share Your Feedback 🏝️

DPO***

DPO***

MinWoo(Daniel) Park | Tech Blog

Read more
Previous: PPO Next: Survey | Evaluating Large Language Models A Comprehensive Survey

DPO***

  • Related Project: Private
  • Category: Paper Review
  • Date: 2023-10-29

Direct Preference Optimization: Your Language Model is Secretly a Reward Model

  • url: https://arxiv.org/abs/2305.18290
  • pdf: https://arxiv.org/pdf/2305.18290
  • html: https://arxiv.org/html/2305.18290v2
  • abstract: While large-scale unsupervised language models (LMs) learn broad world knowledge and some reasoning skills, achieving precise control of their behavior is difficult due to the completely unsupervised nature of their training. Existing methods for gaining such steerability collect human labels of the relative quality of model generations and fine-tune the unsupervised LM to align with these preferences, often with reinforcement learning from human feedback (RLHF). However, RLHF is a complex and often unstable procedure, first fitting a reward model that reflects the human preferences, and then fine-tuning the large unsupervised LM using reinforcement learning to maximize this estimated reward without drifting too far from the original model. In this paper, we leverage a mapping between reward functions and optimal policies to show that this constrained reward maximization problem can be optimized exactly with a single stage of policy training, essentially solving a classification problem on the human preference data. The resulting algorithm, which we call Direct Preference Optimization (DPO), is stable, performant and computationally lightweight, eliminating the need for fitting a reward model, sampling from the LM during fine-tuning, or performing significant hyperparameter tuning. Our experiments show that DPO can fine-tune LMs to align with human preferences as well as or better than existing methods. Notably, fine-tuning with DPO exceeds RLHF’s ability to control sentiment of generations and improves response quality in summarization and single-turn dialogue while being substantially simpler to implement and train.

[DPO 핵심색인마킹]


Contents

TL;DR


  1. 언어 모델을 휴먼 선호(human preference)도에 최적화하는 새로운 접근 방식, Direct Preference Optimization (DPO).
  2. DPO는 보상 모델링이나 강화 학습 없이 간단한 분류 목적으로 정책을 최적화합니다.
  3. 이 연구는 수학적 배경과 논리적 연결을 통해 기존 방법을 단순화하고 효율을 증가시킨다는 것을 입증합니다.

Token-level Direct Preference Optimization Appendix에 대수적으로 깔끔하게 정리된 내용도 있으니 참고하시면 좋습니다.


1. 서론

언어 모델들은 다양한 휴먼의 데이터를 통해 훈련되어 다양한 능력을 획득하지만, 획득한 모든 능력이 항상 바람직하지는 않을 수 있습니다. 예를 들어, 일부 프로그래밍 실수를 인식하고 이를 수정하는 능력은 유용하지만, 모든 쿼리에서 흔한 오해를 진실로 제시하는 것은 바람직하지 않습니다. 이 연구는 기존의 강화 학습 기반 방법을 사용하지 않고도, 직접 선호 최적화(Direct Preference Optimization, DPO)를 통해 언어 모델이 휴먼의 선호도에 맞춰 최적화될 수 있음을 보여줍니다. 이는 간단한 이진 교차 엔트로피 목적함수를 사용하여 간단하고 효율적으로 선호 학습 파이프라인을 최적화합니다.


2. 관련 연구

언어 모델의 성능은 사람들의 선호에 따라 튜닝될 때 상당히 향상될 수 있습니다. 기존 연구들은 주로 강화 학습(RL)과 휴먼의 피드백을 기반으로 모델을 최적화했습니다. 이는 고품질의 대화와 코드 생성 능력을 제공하지만, 복잡한 훈련 과정과 높은 계산 비용을 요구합니다. 이 연구는 이런 접근 방식들을 보완하여, 휴먼의 선호도만을 사용하여 언어 모델을 직접 최적화하는 방법을 제안합니다.


3. 예비 사항

3.1 감독된 파인튜닝 (SFT)

초기 단계에서는 고품질 데이터에 대한 감독된 학습을 통해 언어 모델을 파인튜닝합니다. 이를 통해 모델은 주어진 지시 사항을 이해하고 대응하는 능력을 향상시킬 수 있습니다.

3.2 보상 모델링 단계

보상 모델링 단계에서는 휴먼의 선호도에 따라 선택된 응답 쌍을 제공하고, 이를 통해 보상 함수를 학습합니다. 보상 모델은 Bradley-Terry 모델을 사용하여 선호도를 모델링하며, 선호도의 로지스틱 함수를 통해 최적화합니다.

\[p^*(y_1 \succ y_2 \mid x) = \frac{\exp (r^*(x, y_1))}{\exp (r^*(x, y_1)) + \exp (r^*(x, y_2))} \tag{1}\]

이 모델은 응답의 질을 평가하는데 사용되며, 이진 분류 문제로 구성된 음의 로그 가능도 손실을 최소화하여 파라미터를 추정합니다.

3.3 RL 파인튜닝 단계

강화 학습 단계에서는 학습된 보상 함수를 사용하여 언어 모델의 정책을 최적화합니다. 이 과정은 KL Divergence을 최소화하는 제약 조건 하에 최대 보상을 추구하도록 설계되어 있습니다. 이는 다음과 같은 최적화 문제로 표현될 수 있습니다.

\[\max_{\theta} \mathbb{E}_{x \sim D, y \sim \pi_{\theta}(y\\|x)} [r_{\phi}(x, y)] - \beta \text{KL}(\pi_{\theta}(\cdot\\|x) \\| \pi_{\text{ref}}(\cdot\\|x)) \tag{2}\]

$\beta$는 기준 정책 $\pi_{\text{ref}}$에서의 편차를 조절하는 파라미터입니다. 이 최적화는 일반적으로 PPO를 사용하여 수행되며, 이 연구는 기존의 강화 학습 방법을 사용하지 않고, 직접 선호 최적화를 통해 이런 문제를 해결할 수 있음을 보여줍니다.


4. 직접 선호 최적화 (Direct Preference Optimization, DPO)

대규모 언어모델을 파인튜닝하는 것과 같은 큰 문제에서 강화 학습 알고리즘을 적용하는 데 따르는 챌린지를 극복하기 위해, 직접적인 선호를 사용하여 정책을 최적화하는 간단한 접근 방식을 도출하려고 합니다. 이전 RLHF 방법들이 보상을 학습한 다음 RL을 통해 최적화하는 반면, 접근 방식은 보상 모델 파라미터화의 특정 선택을 활용하여 RL 훈련 루프 없이 최적의 정책을 해석적으로 추출할 수 있게 합니다. 다음으로 자세히 설명할 주요 통찰은 보상 함수에서 최적의 정책으로의 분석적 매핑을 활용하여 보상 함수에 대한 손실 함수를 정책에 대한 손실 함수로 변환하는 것입니다. 이 변수 변환 접근 방식은 명시적인 독립 보상 모델을 적합시키지 않으면서도 휴먼 선호(human preference)의 기존 모델을 최적화합니다. 본질적으로 정책 네트워크는 언어 모델과 (암시적) 보상을 모두 대표합니다.

DPO 목적함수 유도

일반 보상 함수 \(r\) 하에 이전 작업과 동일한 RL 목적함수, Eq. 2에서 시작합니다. 이전 연구들을 따라, Eq. 2에서 KL 제약 조건 하에 보상 최대화 목적함수의 최적 해는 다음과 같은 형태를 취한다는 것을 쉽게 보일 수 있습니다. (본 논문의 Appendix A.1에서 전체 유도 과정을 확인)

\[\pi_r(y\\|x) = \frac{\pi_{\text{ref}}(y\\|x) \exp(r(x, y)/\beta)}{Z(x)} \tag{3}\]

\(Z(x) = \sum_y \pi_{\text{ref}}(y\\|x) \exp(r(x, y)/\beta)\)는 분할 함수

MLE 추정치 \(r_{\phi}\)를 사용하더라도, \(Z(x)\)의 추정은 비용이 많이 들어 실제로 활용하기 어렵습니다. 하지만, Eq. 4를 재정렬하여 보상 함수를 해당 최적 정책 \(\pi_r\), 참조 정책 \(\pi_{\text{ref}}\), 그리고 알려지지 않은 분할 함수 \(Z(\cdot)\)와 관련하여 표현할 수 있습니다.

구체적으로, 양변에 로그를 취한 다음 일부 대수를 사용하여 다음을 얻습니다.

\[r(x, y) = \beta \log \left( \frac{\pi_r(y\\|x)}{\pi_{\text{ref}}(y\\|x)} \right) + \beta \log Z(x) \tag{4}\]

이 재파라미터화를 ground-truth 보상 \(r^*\) 및 해당 최적 모델 \(\pi^*\)에 적용할 수 있습니다.

Bradley-Terry 모델은 두 완성 사이의 보상 차이에만 의존합니다. 즉, \(p^*(y_1 \succ y_2 \mid x) = \sigma(r^*(x, y_1) - r^*(x, y_2))\)입니다. Eq. 4의 재파라미터화를 \(r^*(x, y)\)에 대한 선호 모델 Eq. 1에 대입하면, 분할 함수가 소거되고 휴먼 선호(human preference) 확률을 최적 정책 \(\pi^*\) 및 참조 정책 \(\pi_{\text{ref}}\)만을 사용하여 표현할 수 있으므로 최적의 RLHF 정책 \(\pi^*\)는 선호 모델을 만족합니다.

\[p^*(y_1 \succ y_2 \mid x) = \sigma \left( \beta \log \left( \frac{\pi^*(y_1\\|x)}{\pi_{\text{ref}}(y_1\\|x)} \right) - \beta \log \left( \frac{\pi^*(y_2\\|x)}{\pi_{\text{ref}}(y_2\\|x)} \right) \right) \tag{5}\]

위 수식을 유도하는 식은 Appendix A.2에 자세하게 소개되어 있으며, Eq. 5는 Bradley-Terry 모델을 사용하지만, Appendix A.3에서 보여주듯이 더 일반적인 Plackett-Luce 모델들[30, 21]에서도 유사한 표현을 도출할 수 있습니다.

이제 휴먼 선호 데이터의 확률을 보상 모델이 아닌 최적 정책 측면에서 공식화할 수 있으므로, 파라미터화된 정책 \(\pi_{\theta}\)에 대한 최대 우도 목적함수를 공식화합니다. 보상 모델링 접근 방식(i.e. Eq. 2)과 유사하게, 정책 목적함수는 다음과 같이 표현할 수 있습니다.

\[\mathcal{L}_{\text{DPO}}( ext) = - \sum_{(x, y_w, y_l) \in D} \log \sigma \left( \beta \log \left( \frac{\pi_{\theta}(y_w\\|x)}{\pi_{\text{ref}}(y_w\\|x)} \right) - \beta \log \left( \frac{\pi_{\theta}(y_l\\|x)}{\pi_{\text{ref}}(y_l\\|x)} \right) \right)\]

이 방식으로, 대안적 파라미터화를 사용하여 암시적 보상을 적합시키며, 그 최적 정책은 단순히 \(\pi_{\theta}\)입니다.

이 절차가 Bradley-Terry 모델을 재파라미터화하는 것과 동일하므로, 선호 데이터 분포의 적절한 가정 하에서 일관성을 유지할 수 있을 것이라고 판단합니다. 섹션 5에서 다른 작업들과 관련해 DPO의 이론적 특성에 대해 더 자세히 논의합니다.


5. DPO의 이론적 분석

이 섹션에서는 DPO 방법에 대한 추가적인 해석을 제공하고, 이론적 근거를 제시하며, RLHF(휴먼 피드백으로부터의 강화학습)에 사용되는 액터-크리틱 알고리즘의 문제점들에 대해 DPO의 장점을 연결시킵니다.

5.1 Your Language Model Is Secretly a Reward Model

DPO는 명시적인 보상을 적합시키고 강화학습을 수행하는 과정을 건너뛰고, 단일 최대 우도 목적함수를 사용하여 정책을 학습할 수 있다는 것이 핵심입니다. 최적화 목적함수인 Eq 5.는 보상 파라미터화를 가진 Bradley-Terry 모델과 동일하며, 다음과 같이 표현할 수 있고,

\[r^*(x, y) = \beta \log \frac{\pi^*_{\theta}(y \mid x)}{\pi_{\text{ref}}(y \mid x)}\]

파라미터 모델 \(\pi_{\theta}\)를 최적화합니다.

이는 변수의 변화하에 Eq. 2의 보상 모델 최적화와 동일합니다. 이 절에서는 이 재파라미터화 뒤에 있는 이론을 구축하고, 학습된 보상 모델의 클래스를 제한하지 않으며, 최적의 정책을 정확하게 회복할 수 있음을 보여줍니다.

[정의 1] 보상 함수 \(r(x, y)\)와 \(r'(x, y)\)의 차이는 $y$에 독립적인 어떤 함수 \(f(x)\)로 정의할 수 있다. \(r(x, y) - r'(x, y) = f(x)\)

이것이 등식임을 쉽게 알 수 있으며, 보상 함수의 집합을 클래스로 분할합니다. (본 논문은 이진 분류의 Cross-entropy를 사용해 논리를 전개하므로) 그 뒤 다음 두 가지 Theorem를 제시할 수 있습니다.

  • Theorem 1. Plackett-Luce, 특히 Bradley-Terry, 선호 프레임워크 하에서 같은 클래스의 두 보상 함수는 동일한 선호 분포를 유도한다.
  • Theorem 2. 동일한 동등한 클래스의 두 보상 함수는 제약된 RL 문제 하에서 동일한 최적 정책을 유도한다.



[Theorem 1] Plackett-Luce의 명세 문제

Theorem 1은 Plackett-Luce에서 잘 알려진 명세 문제(Appendix A.5)로, 이 명세 문제를 완화해서 표현하기 위해 Eq. 2에서 MLE 추정 안정화를 위한 추가적인 식별 페널티를 가해줘야 합니다.

Theorem 1의 증명

온건한 가정 하에, Plackett-Luce (특히 Bradley-Terry) 모델과 일관된 모든 보상 클래스는 재파라미터화해 \(r(x, y) = \beta \log \pi(y \mid x)\)로 표현할 수 있고, 어떠한 보상 함수 \(r(x, y)\)는 해당 최적 모델 \(\pi_r(y \mid x)\)를 유도하며, Eq. 4로 표현됩니다. 동등한 클래스의 \(r\)에서 보상 함수를 다음과 주어진 재파라미터화를 사용하여 표현될 수 있음을 보일 것입니다. 투영 \(f\)를 정의합니다.

\[f(r; \pi_{\text{ref}}, \beta)(x, y) = r(x, y) - \beta \log \left( \sum_{y'} \pi_{\text{ref}}(y' \mid x) \exp \left( \frac{r(x, y')}{\beta} \right) \right)\]

연산자 \(f\)는 단순히 보상 함수를 \(\pi_r\)의 분할 함수의 로그와 함께 정규화합니다. 추가된 정규항은 오직 \(x\)에 대한 함수이므로, \(f(r; \pi_{\text{ref}}, \beta)(x, y)\)는 \(r(x, y)\)의 동등한 클래스에 있는 보상 함수입니다.

마지막으로, \(r\)을 Eq. 5의 RHS(어떠한 보상 함수에 대해서도 성립하는)로 대체하면, 다음을 얻습니다.

\[f(r; \pi_{\text{ref}}, \beta)(x, y) = \beta \log \left( \frac{\pi_r(y \mid x)}{\pi_{\text{ref}}(y \mid x)} \right)\]

즉, 투영 \(f\)는 원하는 형태로 동등한 클래스의 \(r\)의 구성원을 생성하며, 제안한 재파라미터화에서 보상 모델의 일반성을 잃지 않습니다.

[Theorem 2] Theorem 1의 증명

Theorem 2는 Theorem 1의 증명을 더 자세히 다룹니다. 동일한 클래스의 모든 보상 함수가 동일한 최적 정책을 산출하므로, 최종 목적함수는 최적 클래스에서 임의의 보상 함수를 회복하는 것에만 집중합니다. (Appendix A.6)

특히, 각 동등한 클래스 내에서 재파라미터화된 보상 함수의 유일성을 보이기 위한 논증에 초점을 맞춥니다.

Theorem 1의 재진술

참조 모델 \(\pi_{\text{ref}}(y\\|x)\)가 모든 프롬프트 \(x\)와 답변 \(y\) 쌍에 대해 0보다 크고, 파라미터 \(\beta > 0\)일 때, 제5장에서 정의된 모든 보상 동등한 클래스는 어떤 모델 \(\pi(y\\|x)\)을 사용해 \(r(x,y) = \beta \log \frac{\pi(y\\|x)}{\pi_{\text{ref}}(y\\|x)}\)로 표현할 수 있게 됩니다.

Theorem 2의 증명

KL 제약이 있는 강화학습 문제에서 최적 모델 \(\pi_r(y\\|x)\)을 유도하는 임의의 보상 함수 \(r(x,y)\)를 고려합니다. 이 문제의 해는 Eq. 4로 설명할 수 있습니다.

\[r(x,y) = \beta \log \frac{\pi_r(y\\|x)}{\pi_{\text{ref}}(y\\|x)} + \beta \log Z(x)\]

\(Z(x) = \sum_y \pi_{\text{ref}}(y\\|x) \exp \left(\text{1}{\beta} r(x,y)\right)\)는 보상 함수 \(r\)에도 의존하는 함수

새로운 보상 함수 \(r'(x,y) = f(r, \pi_{\text{ref}}, \beta)(x,y) = r(x,y) - \beta \log Z(x)\)를 사용하며, 이 보상 함수는 \(r\)의 동등한 클래스 내에 있으므로 결론적으로 다음과 같은 식을 통해 증명을 완결합니다.

\[r'(x, y) = \beta \log \frac{\pi_r(y\\|x)}{\pi_{\text{ref}}(y\\|x)}\]

결과를 확장해 만약 \(r\)과 \(r'\)이 같은 클래스의 두 보상 함수라면, 다음이 성립함을 알 수 있습니다.

\[f(r, \pi_{\text{ref}}, \beta)(x,y) = \beta \log \frac{\pi_r(y\\|x)}{\pi_{\text{ref}}(y\\|x)} = \beta \log \frac{\pi'_r(y\\|x)}{\pi_{\text{ref}}(y\\|x)} = f(r', \pi_{\text{ref}}, \beta)(x,y)\]

두 번째 등식은 Theorem 2에서 유도한 것이고, \(f\) 연산자가 특정 동등한 클래스의 모든 보상 함수를 동일한 보상 함수로 매핑한다는 것을 증명했습니다.


다음으로, 각 보상 함수의 동등한 클래스에 대해, 정리 1에서 설명된 재파라미터화를 통해 표현할 수 있는 유일한 보상 함수가 있음을 보여줍니다.

[명제 1]

참조 모델 \(\pi_{\text{ref}}(y\\|x)\)가 모든 프롬프트 \(x\)와 답변 \(y\) 쌍에 대해 0보다 크고, 파라미터 \(\beta > 0\)일 때, 제5장에서 정의된 모든 보상 동등한 클래스는 어떤 모델 \(\pi(y\\|x)\)을 사용하여 \(r(x,y) = \beta \log \frac{\pi(y\\|x)}{\pi_{\text{ref}}(y\\|x)}\)로 유일하게 재파라미터화될 수 있다.

[명제 1]의 증명

모순을 증명하기 위해 동일한 클래스에 속하는 두 개의 보상 함수 \(r'\)과 \(r\)가 있으며, \(r'(x,y) = r(x,y) + f(x)\)라고 가정합니다.

또한 \(r'(x,y) = \beta \log \frac{\pi'(y\\|x)}{\pi_{\text{ref}}(y\\|x)}\)이고, \(r(x,y) = \beta \log \frac{\pi(y\\|x)}{\pi_{\text{ref}}(y\\|x)}\)이며 \(\pi = \pi'\)이므로 다음 식이 성립합니다.

\[r'(x, y) = r(x,y) + f(x) = \beta \log \frac{\pi(y\\|x)}{\pi_{\text{ref}}(y\\|x)} \exp\left(\text{1}{\beta} f(x)\right) = \beta \log \frac{\pi'(y\\|x)}{\pi_{\text{ref}}(y\\|x)}\]

모든 \(x\)와 \(y\)에 대해 \(\pi(y\\|x) \exp\left(\text{1}{\beta} f(x)\right) = \pi'(y\\|x)\)라고 할 때,

이들은 분포이므로 양 변을 \(y\)에 대해 정리하면

\(\exp\left(\text{1}{\beta} f(x)\right) = 1\)이고,

\(\beta > 0\)이므로 \(f(x) = 0\)이어야 하므로, \(r(x,y) = r'(x,y)\)입니다.

이제 모든 보상 클래스가 [Theorem 1]에서 설명한 재파라미터화로 표현될 수 있는 유일한 보상 함수를 가진다는 것을 보였습니다.

소결: 따라서 앞으로 이 보상 함수는 해당 클래스의 어떤 보상 함수에 대해서도 \(f(r, \pi_{\text{ref}}, \beta)\)로 주어지게 됩니다.


5.2 액터-크리틱 알고리즘의 불안정성

[DPO의 불안정성 및 유의사항 색인마킹]

이 섹션에서는 RLHF(휴먼 피드백을 통한 강화 학습)에서 사용되는 표준 액터-크리틱 알고리즘, 예를 들어 PPO(Proximal Policy Optimization)의 불안정성을 확인하기 위해 프레임워크를 사용합니다. RLHF 파이프라인을 따르며 섹션 3에 기술된 제약된 RL 문제의 프레임워크와 연결하며, 파라미터화된 모델 \(\pi_{\theta}(y \mid x)\)를 가정하고 최적화 목적함수를 다음과 같이 설정합니다.

\[\mathcal{L}_{\text{RLHF}}( ext) = -\mathbb{E}_{(x,y) \sim D} \left[ r_{\phi}(x, y) - \beta (\log \pi_{\theta}(y \mid x) - \log \pi_{\text{ref}}(y \mid x)) \right]\]

이 목적함수는 이전 연구에서 사용된 DPO-동등 보상과 동일한 목적함수를 최적화합니다. 이 셋팅에서, \(f (r_{\phi}, \pi_{\text{ref}}, \beta)\)의 정규항을 참조 정책 \(\pi_{\text{ref}}\)의 소프트 값 함수로 해석할 수 있으며, 이 정규항은 최적 솔루션에 영향을 미치지 않지만, 이 항 없이는 목적함수의 Policy Gradient의 분산이 높아져 학습이 불안정해질 수 있습니다. 학습된 값 함수를 사용하여 이 정규항을 수용할 수 있지만, 그것 역시 최적화를 장담하기 어려울 수 있습니다.

대안으로 이전 연구들은 휴먼 완성 기준을 사용하여 보상을 정규화했으며, 이는 정규항의 단일 샘플 몬테카를로 추정에 해당합니다. 반면, DPO의 재파라미터화는 기준 없이 보상 함수를 제공합니다.


6. DPO의 안정성과 효율성의 이론적 분석

DPO의 재파라미터화 접근 방식은 기존의 액터-크리틱 방법이 겪는 몇 가지 주요 문제들을 해결합니다. 특히, 보상 함수를 직접 정책 훈련 과정에 통합함으로써, 보상의 정규화를 내재화하고, 이로 인해 학습 중 발생할 수 있는 높은 분산 문제를 감소시킵니다. 이런 접근 방식은 보상 함수의 복잡성을 줄이면서도 정책의 최적화를 단순화하며, 보다 안정적인 학습 동작을 촉진합니다.

  • DPO의 효율성: 휴먼 피드백으로부터 강화 학습(RLHF) 목표를 효율적으로 최적화하는 DPO의 능력을 분석하고, 다른 알고리즘에 비해 우수한 보상/KL 트레이드오프를 달성합니다.
  • 실제 데이터에 대한 확장성: 요약과 대화와 같은 실제 응용 프로그램에서 DPO의 효과성을 보여주며, 다양한 데이터셋에서 기존 방법보다 우수한 성능을 보입니다.
  • 휴먼 판단과의 검증: GPT-4의 휴먼 평가 대리자로서의 신뢰성을 비교 휴먼 연구를 통해 확립하고, 자동 평가를 위해 GPT-4 사용을 지지합니다.

이론적 이점 외에도, DPO는 여러 실제 시나리오에서 PPO 같은 기존 액터-크리틱 알고리즘들보다 우수한 성능을 보이는 것으로 나타났습니다. 특히, 다양한 샘플링 온도에서의 안정성과 효율성을 보여주는 실험 결과가 이를 뒷받침합니다.

이 섹션의 분석은 DPO가 기존의 RL 알고리즘들과 비교하여 어떻게 더 높은 보상과 낮은 KL Divergence을 달성하는지를 확인합니다.


6.1 DPO가 RLHF 목표를 최적화하는 효율성

DPO(직접 정책 최적화)는 보상 극대화와 낮은 KL-발산을 유지하는 이중 목표 사이의 균형을 PPO(접근 정책 최적화)와 같은 알고리즘에 비해 주목할만하게 효율적으로 달성합니다. IMDb 데이터셋을 사용한 감정 분석 작업에서 DPO의 성능은 보상과 KL 차이가 낮은 경쟁자보다 높은 보상을 달성할 수 있는 프론티어 곡선을 통해 그래픽으로 표현됩니다. 보상-KL 프론티어의 수학적 표현은 정책 보수성을 수정하기 위해 하이퍼파라미터를 조정하는 다수의 실행에서 파생됩니다.

\[\text{KL}(\pi \\| \pi_{\text{ref}}) = \sum_{t=1}^T \text{KL}(\pi_t \\| \pi_{\text{ref},t})\]

\(\pi\) 와 \(\pi_{\text{ref}}\)는 각각 정책 및 참조 정책 분포

이 측정치는 학습된 정책이 사전 설정된 참조에서 얼마나 벗어나는지를 정량화하여, DPO가 성능을 최적화하는 동안 원하는 행동에 밀접하게 부합하는 효과성을 강조합니다.


6.2 실제 선호 데이터셋에 DPO 확장

Reddit TL;DR 및 Anthropic HH 데이터셋을 사용한 요약 및 단일 턴 대화 작업에 적용될 때, DPO는 0-shot 프롬프팅 및 PPO 최적화 모델을 포함한 표준 방법보다 성능이 뛰어납니다. 사용된 평가 척도인 “승률”은 DPO가 생성한 요약이나 대화가 기준 방법에서 생성된 것보다 선호된 시험의 비율로 정의됩니다. 이는 다음과 같이 정량화됩니다.

\[\text{Win Rate} = \frac{\text{Number of preferred DPO completions}}{\text{Total completions evaluated}}\]

DPO는 다양한 샘플링 온도(temperature)에서 견고함을 보여주며, 광범위한 하이퍼파라미터 조정 없이도 사용자 선호에 적응할 수 있음을 시사합니다.


6.3 DPO와 PPO의 일반화

새로운 입력 분포로의 일반화 맥락에서, DPO와 PPO는 CNN/DailyMail의 뉴스 기사와 같은 다른 도메인에서 테스트됩니다. 데이터 유형이 변경되었음에도 불구하고 DPO는 PPO 정책보다 눈에 띄게 우수한 성능을 보이며, DPO 정책이 PPO 정책만큼 잘 일반화될 수 있다는 초기 증거를 제공합니다.


7 토론

선호도에서 학습하는 것은 능력 있는, 조화로운 언어 모델을 훈련하기 위한 강력하고 확장 가능한 프레임워크입니다. 강화학습 없이 선호도에서 언어 모델을 훈련하는 간단한 훈련 패러다임인 DPO를 소개했습니다. 기존의 RL 알고리즘을 사용하기 위해 선호 학습 문제를 표준 RL 설정으로 강제하는 대신, DPO는 언어 모델 정책과 보상 함수 사이의 매핑을 확인하여, 강화학습이나 일반성 손실 없이, 단순한 교차 엔트로피 손실을 사용하여 휴먼의 선호도를 직접 만족시키는 언어 모델을 훈련할 수 있게 합니다.

거의 하이퍼파라미터 조정 없이도, DPO는 기존의 RLHF 알고리즘, 특히 PPO 기반 알고리즘과 비교하여 유사하거나 더 나은 성능을 보이므로 DPO는 휴먼의 선호도에서 더 많은 언어 모델을 훈련하는 장벽을 의미 있게 낮출 수 있습니다.


8 제한사항 및 향후 연구

  • Q1. DPO 정책이 명시적 보상 함수에서 학습하는 것과 비교하여 분포 외에서 어떻게 일반화되나?

    초기 결과는 DPO 정책이 PPO 기반 모델과 유사하게 일반화될 수 있다는 것을 시사하지만, 더 포괄적인 연구가 필요하다고 언급합니다.

  • Q2. DPO 정책에서 자가 레이블링을 통한 훈련이 레이블이 없는 프롬프트를 효과적으로 활용할 수 있나?

  • Q3. 직접 선호 최적화 설정에서 보상 과잉 최적화가 어떻게 나타나며, Figure 3-오른쪽의 성능 소폭 감소가 그 예인가?

최대 6B 파라미터의 모델을 평가했지만, 향후 작업에서는 훨씬 더 큰 규모의 SOTA 모델로 DPO를 확장하는 것 역시 추가 연구가 필요하다고 언급합니다. 평가와 관련하여, GPT-4에 의해 계산된 승률이 프롬프트에 의해 영향을 받는다는 것을 발견했으며, 향후 연구는 자동 시스템에서 고품질 판단을 이끌어내는 최선의 방법을 연구할 수 있습니다.

마지막으로, 휴먼의 선호도에서 언어 모델을 훈련하는 것을 넘어 DPO를 응용하여 적용할 수 있으며, 다른 모달리티에서 생성 모델을 훈련하는 것도 포함될 수 있습니다.



Appendix

A.1 KL 제약 보상 최대화 목표의 최적화 유도

배경 및 목표 설정

본 절에서는 기대 보상을 최대화하면서 주어진 참조 모델 \(\pi_{\text{ref}}\)과의 KL Divergence을 최소화하는 정책 \(\pi\)를 찾는 문제를 다룹니다. 이 최적화 과정은 일반적으로 강화학습에서 보상을 최대화하는 동시에 정책의 변동성을 제어하기 위해 사용됩니다.

Eq. 11

\(\max_\pi \mathbb{E}_{x \sim D, y \sim \pi} [r(x,y) - \beta D_{KL}(\pi(y|x) \\| \pi_{\text{ref}}(y|x))]\)

  • 목적함수 설명: \(r(x, y)\)는 보상 함수, \(\beta\)는 정규화 팩터, \(D_{KL}\)는 두 확률 분포 사이의 KL Divergence을 나타냅니다.
  • 최적화 접근: 정책 \(\pi\)가 주어진 \(x\)에 대해 어떤 \(y\)를 선택할지 결정하는 확률 모델로 작용하며, 이는 참조 모델 \(\pi_{\text{ref}}\)로부터 크게 벗어나지 않는 범위 내에서 최대 보상을 추구합니다.

변환 및 파티션 함수 \(Z(x)\) 도입

  • 파티션 함수 정의: \(Z(x)\)는 모든 가능한 \(y\)에 대해 정규화된 합을 제공하여 확률 분포를 유지합니다.
  • 수식 변환: \(Z(x) = \sum_y \pi_{\text{ref}}(y|x) \exp\left(\text{1}{\beta} r(x,y)\right)\) \(\pi^*(y|x) = \frac{1}{Z(x)} \pi_{\text{ref}}(y|x) \exp\left(\text{1}{\beta} r(x,y)\right)\) 이는 \(\pi^*\)가 \(\pi_{\text{ref}}\)를 기반으로 보상을 고려하여 조정된 확률 분포임을 보여줍니다.


A.2 Bradley-Terry(브래들리-테리) 모델 하의 DPO 목표 유도

Eq. 16, 17

  • Bradley-Terry 모델: 이 모델은 두 대안 \(y_1\), \(y_2\) 사이의 선택 확률을 보상 함수를 통해 비교합니다.
  • 수식 전개: \(p^*(y_1 \succ y_2|x) = \sigma\left(\beta \log \frac{\pi^*(y_1|x)}{\pi_{\text{ref}}(y_1|x)} - \beta \log \frac{\pi^*(y_2|x)}{\pi_{\text{ref}}(y_2|x)}\right)\) \(\sigma\)는 시그모이드 함수를 나타내며, 두 정책 간의 로그 확률 비를 확률적 선호도로 변환합니다.


A.3 Plackett-Luce(플래킷-루스) 모델 하의 DPO 목표 유도

Eq. 18, 19

  • Plackett-Luce 모델: 랭킹을 통해 여러 대안들 사이의 선호를 모델링합니다. 이는 Bradley-Terry 모델을 확장한 것으로, 복수의 대안들 간의 상대적 가치를 평가할 수 있습니다.
  • 수식 전개

    \[p^*(\tau|y1, ..., yK, x) = \prod_{k=1}^K \frac{\exp(\beta \log \frac{\pi^*(y_{\tau(k)}|x)}{\pi_{\text{ref}}(y_{\tau(k)}|x)})}{\sum_{j=k}^K \exp(\beta \log \frac{\pi^*(y_{\tau(j)}|x)}{\pi_{\text{ref}}(y_{\tau(j)}|x)})}\]

    각 순위 \(k\)에 대해, \(y_{\tau(k)}\)가 선택될 조건부 확률을 계산합니다. 이는 전체 순위의 확률 분포를 제공합니다.


A.4 유도: DPO 목표의 Gradient

Eq 21

\[\nabla_\theta \mathcal{L}_{DPO}(\pi_\theta; \pi_{\text{ref}}) = -\nabla_\theta \mathbb{E}_{(x, y_w, y_l) \sim \mathcal{D}} [\log \sigma(\beta \log \frac{\pi_\theta(y_l|x)}{\pi_{\text{ref}}(y_l|x)} - \beta \log \frac{\pi_\theta(y_w|x)}{\pi_{\text{ref}}(y_w|x)})]\]

이 수식은 두 정책 간의 로그 비율의 차이에 대한 시그모이드 함수의 로그를 최적화하는 Gradient를 구하는 과정으로, \(y_l\)과 \(y_w\)는 각각 승리와 패배를 나타내는 행동을 의미합니다.

Eq 22로의 변환

\[\nabla_\theta \mathcal{L}_{DPO}(\pi_\theta; \pi_{\text{ref}}) = -\mathbb{E}_{(x, y_w, y_l) \sim \mathcal{D}} [\sigma'(\beta u) \frac{\sigma(\beta u)}{\sigma(\beta u)} \nabla_\theta u]\]

\(u = \beta \log \frac{\pi_\theta(y_l\\|x)}{\pi_{\text{ref}}(y_l\\|x)} - \beta \log \frac{\pi_\theta(y_w\\|x)}{\pi_{\text{ref}}(y_w\\|x)}\)는 시그모이드 함수의 입력이며, \(\sigma'(x) = \sigma(x)(1 - \sigma(x))\)라는 시그모이드 함수의 특성을 이용하여 Gradient를 계산합니다.

최종 Gradient 형식

이런 접근 방식은 보상 함수의 Gradient를 이용하여 정책의 파라미터를 직접 조정할 수 있는 방법을 제공합니다. 이는 강화학습에서 주어진 상황에 가장 적합한 행동을 선택하는 정책을 진화시키는 데 사용됩니다.


A.5 Lemma 1 및 2의 증명

Lemma 1

Lemma 1 재진술: Plackett-Luce 및 Bradley-Terry 프레임워크에서 동일한 동등한 클래스에 속하는 두 보상 함수는 동일한 선호 분포를 유도한다.

증명: 두 보상 함수 \(r(x, y)\)와 \(r'(x, y)\)가 동일한 동등한 클래스에 속한다고 가정하면, \(r'(x, y) = r(x, y) + f(x)\)로 표현할 수 있습니다. Plackett-Luce 모델에서 각 순위에 대한 확률은 다음과 같이 표현됩니다.

\[p_{r'}(\tau|y1, \dots, yK, x) = \prod_{k=1}^K \frac{\exp(r'(x, y_{\tau(k)}))}{\sum_{j=k}^K \exp(r'(x, y_{\tau(j)}))}\]

함수 \(f(x)\)가 추가되어도 전체 분모와 분자에서 상쇄되므로, 두 함수는 동일한 순위 확률을 유도합니다.

Lemma 2

Lemma 2 재진술: 동일한 동등한 클래스에 속하는 두 보상 함수는 제약이 있는 강화학습 문제에서 동일한 최적 정책을 유도한다.

증명: 두 보상 함수 \(r(x, y)\)와 \(r'(x, y) = r(x, y) + f(x)\)가 주어졌을 때, 각각의 최적 정책을 \(\pi_r\)과 \(\pi_{r'}\)로 표시하면, 모든 \(x, y\)에 대해 다음이 성립합니다.

\[\pi_{r'}(y|x) = \frac{\exp(\text{1}{\beta}(r'(x, y)))}{\sum_y \exp(\text{1}{\beta}(r'(x, y)))} = \frac{\exp(\text{1}{\beta}(r(x, y) + f(x)))}{\sum_y \exp(\text{1}{\beta}(r(x, y) + f(x)))}\]

\(f(x)\)가 추가되어도 분모와 분자에서 상쇄되므로, 두 정책은 동일합니다.

A.6 정리 1의 증명

정리 1 재진술

모든 보상 동등한 클래스는 섹션 5에서 정의된 바와 같이 \(r(x, y) = \beta \log \frac{\pi(y\\|x)}{\pi_{\text{ref}}(y\\|x)}\)로 재파라미터화될 수 있다고 가정합니다.

증명: 임의의 보상 함수 \(r(x, y)\)가 KL 제약 RL 문제에서 최적 모델 \(\pi_r(y\\|x)\)을 유도하고, 이는 Eq 4에 의해 주어집니다. 양변을 로그 선형화하면 다음을 얻습니다.

\[r(x, y) = \beta \log \frac{\pi_r(y\\|x)}{\pi_{\text{ref}}(y\\|x)} + \beta \log Z(x)\]

\(Z(x) = \sum_y \pi_{\text{ref}}(y\\|x) \exp(\text{1}{\beta} r(x, y))\)이며, 이는 보상 함수 \(r\)에도 의존합니다. \(r'(x, y) = r(x, y) - \beta \log Z(x)\)를 사용하여 새로운 보상 함수가 \(r\)의 동등한 클래스 내에 있음을 확인할 수 있습니다.

이 증명을 통해 각 동등한 클래스에는 정리 1에 설명된 재파라미터화를 통해 나타낼 수 있는 고유한 보상 함수가 존재함을 보입니다.


[참고자료 1] Bradley-Terry와 Plackett-Luce 모델의 이해

Bradley-Terry와 Plackett-Luce 모델은 선택 가능한 대안들 사이의 상대적 선호도를 수학적으로 모델링하는 방법입니다. 이런 모델들은 사회과학, 통계학, 심리학, 그리고 머신 러닝 등 다양한 분야에서 널리 사용되며, 특히 순위 매기기와 결정 분석에서 중요한 역할을 합니다.

Bradley-Terry 모델의 기초

Bradley-Terry 모델은 두 대안 사이의 선택 확률을 모델링하는 방법을 제공합니다. 기본적인 아이디어는 각 대안이 어떤 ‘강도’나 ‘능력’을 가지고 있으며, 이 강도에 기반하여 선택 확률이 결정된다는 것입니다.

수학적 정의

대안 \(A\)와 \(B\)의 강도를 각각 \(\pi_A\)와 \(\pi_B\)라 할 때, 대안 \(A\)가 \(B\)를 선택할 확률은 다음과 같이 표현됩니다.

\[P(A \succ B) = \frac{\pi_A}{\pi_A + \pi_B}\]

이 공식은 \(A\)와 \(B\)가 대결했을 때, \(A\)의 승리 확률을 나타내며, 강도의 상대적 비율에 따라 결정됩니다.

예시

예를 들어, 테니스 선수 A와 B가 대결한다고 가정해 봅시다. A의 강도가 70, B의 강도가 30이라면, A가 승리할 확률은

\[P(A \succ B) = \frac{70}{70 + 30} = \frac{70}{100} = 0.7\]

즉, A가 B를 이기는 확률은 70%입니다.

Plackett-Luce 모델의 확장

Plackett-Luce 모델은 Bradley-Terry 모델을 여러 대안이 경쟁하는 상황으로 확장한 것입니다. 이 모델은 순위 데이터를 처리할 수 있으며, 각 대안이 순위에 따라 확률적으로 선택됩니다.

수학적 정의

대안들의 집합 \(\{A_1, A_2, ..., A_k\}\) 가 주어졌을 때, 첫 번째로 선택될 대안 \(A_i\)의 확률은 다음과 같이 주어집니다. \(P(A_i \text{ is first}) = \frac{\pi_{A_i}}{\sum_{j=1}^k \pi_{A_j}}\) 선택된 대안은 집합에서 제거되며, 남은 대안들에 대해 동일한 계산을 반복하여 순위를 결정합니다.

예시

대안 \(A, B, C\)가 있고, 각각의 강도가 50, 25, 25라면, \(A\)가 첫 번째로 선택될 확률은

\(P(A \text{ is first}) = \frac{50}{50 + 25 + 25} = \frac{50}{100} = 0.5\) \(A\)가 선택된 후, \(B\)와 \(C\) 사이에서 \(B\)가 선택될 확률은 \(P(B \text{ is first after } A) = \frac{25}{25 + 25} = 0.5\)

이와 같이 각 단계마다 대안을 선택하고, 그 선택 확률을 업데이트하여 최종 순위를 결정합니다.

이 모델들은 토너먼트나 스포츠 경기의 예측, 제품 또는 서비스의 선호도 조사, 심지어는 검색 엔진이나 추천 시스템에서 결과를 순위별로 나열할 때도 활용됩니다. 데이터에서 숨겨진 선호도나 강도를 인퍼런스하고 이를 바탕으로 미래의 선택을 예측하는 데 유용합니다.

이런 모델들은 단순하지만 강력한 도구로서, 복잡한 결정 과정을 이해하고 예측하는 데 필수적인 역할을 합니다. 또한, 다양한 변수와 상황에 따라 모델을 적절히 조정하고 확장하는 것이 중요하며, 이를 통해 보다 정확하고 신뢰할 수 있는 예측을 도출할 수 있습니다.


[참고자료 2] Bradley-Terry와 Plackett-Luce 모델을 DPO(Differential Preference Optimization)에서의 활용

Bradley-Terry 모델과 Plackett-Luce 모델은 서로 다른 선택지 간의 선호도를 모델링하는 데 사용되는 통계적 접근 방식입니다. 이 두 모델은 강화학습 분야에서 특히 중요한 역할을 하며, DPO라는 최적화 기법에서 핵심적으로 활용됩니다. 이 섹션에서는 두 모델의 기본 수학적 구조를 살펴보고, DPO에서의 구체적인 활용 방법에 대해 자세히 설명하겠습니다.

Bradley-Terry 모델의 기본 수식

Bradley-Terry 모델은 두 대안 \(y_1\)과 \(y_2\) 사이의 상대적 선호도를 다음과 같이 모델링합니다.

\[p(y_1 \succ y_2 \\| x) = \frac{\exp(\beta \pi(y_1\\|x))}{\exp(\beta \pi(y_1\\|x)) + \exp(\beta \pi(y_2\\|x))}\]

\(\pi(y\\|x)\)는 주어진 상황 \(x\)에서 대안 \(y\)의 선호도를 나타내는 함수이고, \(\beta\)는 모델의 감도를 조절하는 파라미터입니다.

Plackett-Luce 모델의 확장

Plackett-Luce 모델은 랭킹 시스템에서 여러 선택지의 선호도를 순위화하는 데 사용됩니다. 이 모델은 다음과 같은 수식으로 표현됩니다.

\[P(\tau \\| y_1, \dots, y_K, x) = \prod_{k=1}^K \frac{\exp(\beta \pi(y_{\tau(k)}\\|x))}{\sum_{j=k}^K \exp(\beta \pi(y_{\tau(j)}\\|x))}\]

이 식에서 \(\tau\)는 \(K\)개의 선택지 \(y_1, \dots, y_K\)에 대한 순위 순열을 나타냅니다.

DPO에서의 활용

DPO는 주어진 데이터셋을 바탕으로 시스템이 사용자의 선호도 차이를 학습하고 최적화하는 프로세스입니다. DPO에서는 Bradley-Terry 또는 Plackett-Luce 모델을 사용하여 대안 간의 선호도를 비교하고, 이를 통해 정책 \(\pi\)를 학습합니다.

선호도 모델링

DPO에서 Bradley-Terry 모델은 두 대안의 선호도를 비교하여 각 결정의 확률적 결과를 예측하는 데 사용됩니다. 예를 들어, 두 제품 \(A\)와 \(B\) 중 사용자가 \(A\)를 선택할 확률을 계산하여, 이 데이터를 통해 시스템이 더 매력적인 제품을 추천하도록 학습합니다.

최적화 과정

DPO의 최적화 과정에서는 Plackett-Luce 모델을 사용하여 다수의 대안 중 사용자가 가장 선호하는 순서를 예측합니다. 이 모델은 각 순위의 선택 확률을 계산하고, 이를 최적화하여 최종적으로 사용자의 선호도에 가장 잘 맞는 순서를 제시합니다.

Gradient 기반 학습

DPO에서는 선택된 선호도 모델의 Gradient를 계산하여 정책 네트워크를 업데이트합니다. 이 과정은 로그-우도 함수의 최대화를 통해 이루어지며, 각 선택이 최종 선호도에 미치는 영향을 평가하여 정책을 조정합니다. [참고자료 3]

LLM에서의 활용

예를 들어, LLM A와 B에 대해서 rejected-choiced 쌍 데이터셋을 통해 DPO를 사용하여 정책의 선호도를 계산하고, 이를 바탕으로 사용자가 가장 선호할 것으로 예상되는 정책에 근접하게 Gradient를 업데이트할 수 있습니다.

결론적으로 DPO (Differential Preference Optimization)에서는 Bradley-Terry 모델을 사용하는 것이 일반적인데, 이는 Plackett-Luce 모델이 Bradley-Terry 모델을 확장한 형태로 다수의 대안 간의 순위를 결정할 수 있지만, 데이터셋의 레이블링의 공수 및 난도로부터 기인합니다. 즉, 현재 대다수 모델에서 사용하는 Alignment Tuning의 한 종류인 DPO는 choiced-rejected의 항을 토대로 학습하는 것을 기본으로 하기 때문입니다.

Bradley-Terry와 Plackett-Luce 모델은 간단하지만 강력한 도구로서, DPO와 같은 최적화 기법에서 중요한 역할을 합니다. 이런 모델을 통해 다양한 선택지 간의 선호도를 정량화하고, 이 데이터를 기반으로 사용자에게 최적화된 결정을 제공할 수 있습니다.


[참고자료 3] DPO에서 최적화와 로그-우도 함수의 최대화 상세 설명

DPO (Differential Preference Optimization) 과정에서는 로그-우도 함수를 최대화하여 모델이 데이터에 내재된 패턴을 학습하게 됩니다. 이 과정은 머신러닝에서 일반적으로 사용되는 방법이며, 특히 강화학습과 선택 모델링에서 중요합니다.

로그-우도(Log-Likelihood)란?

로그-우도 함수는 주어진 모델이 데이터를 생성할 확률의 로그를 취한 것입니다. 모델이 데이터를 잘 설명할수록, 즉 데이터가 모델에서 나올 가능성이 높을수록 로그-우도 값은 커집니다. 로그-우도를 사용하는 이유는 수학적으로 다루기 편리하고, 곱셈 대신 덧셈 연산을 사용할 수 있기 때문에 계산상 이점이 있습니다.

수학적 정의

\[\log L( ext\\|data) = \sum_{i=1}^n \log P(data_i\\|\theta)\]

\(\theta\)는 모델의 파라미터, \(data\)는 관측된 데이터, \(P(data_i\\|\theta)\)는 파라미터 \(\theta\)를 사용했을 때 데이터 포인트 \(data_i\)의 확률입니다.

Gradient 활용

모델을 학습시키기 위해서는 로그-우도 함수를 최대화하는 파라미터 \(\theta\)를 찾아야 합니다. 이를 위해 Gradient(기울기)를 계산하고, 이를 사용하여 파라미터를 업데이트하는 경사 상승법(또는 경사 하강법의 반대)을 적용합니다.

Gradient는 로그-우도 함수의 각 파라미터에 대한 미분값으로, 파라미터를 조금 변경했을 때 로그-우도가 어떻게 변하는지를 나타냅니다. 이 정보를 바탕으로 파라미터를 조정하며 로그-우도를 최대화할 수 있는 방향으로 이동시킵니다.

Gradient 업데이트 공식

\[\theta^{(new)} = \theta^{(old)} + \eta \nabla_\theta \log L( ext\\|data)\]

\(\eta\)는 학습률(learning rate)

두 LLM A와 B의 응답 비교

사용자가 특정 질문에 대한 두 가지 LLM의 응답 A와 B를 평가한다고 가정(DPO에서는 choiced와 rejected의 쌍 데이터셋을 활용)하면, DPO의 목표는 사용자가 더 선호할 응답을 예측하도록 LLM의 파라미터를 업데이트하는 거라고 볼 수 있습니다.

데이터 모델링

  • LLM A와 B의 응답 각각에 대한 사용자의 선호도를 \(\pi_A\)와 \(\pi_B\)라고 가정합시다.
  • Bradley-Terry 모델을 사용하여 선호도를 모델링:

    \[P(A \succ B) = \frac{\exp(\pi_A)}{\exp(\pi_A) + \exp(\pi_B)}\]

로그-우도 함수

  • 사용자가 A를 선호한다는 데이터가 주어졌다면, 로그-우도 함수는 다음과 같이 됩니다.

    \[\log L = \log \frac{\exp(\pi_A)}{\exp(\pi_A) + \exp(\pi_B)}\]
  • 이 함수를 최대화하면, 사용자의 선호도를 가장 잘 반영하는 파라미터 \(\pi_A\)와 \(\pi_B\)를 추정할 수 있습니다.

Gradient 계산과 업데이트

  • Gradient를 계산하고 파라미터를 업데이트하여, 점진적으로 모델이 사용자의 선호도를 더 정확하게 반영하도록 학습됩니다.
  • 이 과정은 반복적으로 수행되며, 매 반복마다 파라미터가 조금씩 조정됩니다.

사용자 데이터를 바탕으로 로그-우도를 계산하고, 이를 최대화하기 위해 모델 파라미터를 조정하면서, 최종적으로 사용자가 가장 선호할 가능성이 높은 응답을 예측합니다.


1 Introduction

Large unsupervised language models (LMs) trained on very large datasets acquire surprising capabilities [11, 7, 40, 8]. However, these models are trained on data generated by humans with a wide variety of goals, priorities, and skillsets. Some of these goals and skillsets may not be desirable to imitate; for example, while we may want our AI coding assistant to understand common programming mistakes in order to correct them, nevertheless, when generating code, we would like to bias our model toward the (potentially rare) high-quality coding ability present in its training data. Similarly, we might want our language model to be aware of a common misconception believed by 50% of people, but we certainly do not want the model to claim this misconception to be true in 50% of queries about it! In other words, selecting the model’s desired responses and behavior from its very wide knowledge and abilities is crucial to building AI systems that are safe, performant, and controllable [26]. While existing methods typically steer LMs to match human preferences using reinforcement learning (RL), 37th Conference on Neural Information Processing Systems (NeurIPS 2023). we will show that the RL-based objective used by existing methods can be optimized exactly with a simple binary cross-entropy objective, greatly simplifying the preference learning pipeline.

Figure 1: DPO optimizes for human preferences while avoiding reinforcement learning. Existing methods for fine-tuning language models with human feedback first fit a reward model to a dataset of prompts and human preferences over pairs of responses, and then use RL to find a policy that maximizes the learned reward. In contrast, DPO directly optimizes for the policy best satisfying the preferences with a simple classification objective, fitting an implicit reward model whose corresponding optimal policy can be extracted in closed form.

At a high level, existing methods instill the desired behaviors into a language model using curated sets of human preferences representing the types of behaviors that humans find safe and helpful. This preference learning stage occurs after an initial stage of large-scale unsupervised pre-training on a large text dataset. While the most straightforward approach to preference learning is supervised fine-tuning on human demonstrations of high quality responses, the most successful class of methods is reinforcement learning from human (or AI) feedback (RLHF/RLAIF; [12, 2]). RLHF methods fit a reward model to a dataset of human preferences and then use RL to optimize a language model policy to produce responses assigned high reward without drifting excessively far from the original model. While RLHF produces models with impressive conversational and coding abilities, the RLHF pipeline is considerably more complex than supervised learning, involving training multiple LMs and sampling from the LM policy in the loop of training, incurring significant computational costs.

In this paper, we show how to directly optimize a language model to adhere to human preferences, without explicit reward modeling or reinforcement learning. We propose Direct Preference Optimization (DPO), an algorithm that implicitly optimizes the same objective as existing RLHF algorithms (reward maximization with a KL-divergence constraint) but is simple to implement and straightforward to train. Intuitively, the DPO update increases the relative log probability of preferred to dispreferred responses, but it incorporates a dynamic, per-example importance weight that prevents the model degeneration that we find occurs with a naive probability ratio objective. Like existing algorithms, DPO relies on a theoretical preference model (such as the Bradley-Terry model; [5]) that measures how well a given reward function aligns with empirical preference data. However, while existing methods use the preference model to define a preference loss to train a reward model and then train a policy that optimizes the learned reward model, DPO uses a change of variables to define the preference loss as a function of the policy directly. Given a dataset of human preferences over model responses, DPO can therefore optimize a policy using a simple binary cross entropy objective, producing the optimal policy to an implicit reward function fit to the preference data.

Our main contribution is Direct Preference Optimization (DPO), a simple RL-free algorithm for training language models from preferences. Our experiments show that DPO is at least as effective as existing methods, including PPO-based RLHF, for learning from preferences in tasks such as sentiment modulation, summarization, and dialogue, using language models with up to 6B parameters.

Self-supervised language models of increasing scale learn to complete some tasks zero-shot [31] or with few-shot prompts [6, 25, 11]. However, their performance on downstream tasks and alignment with user intent can be significantly improved by fine-tuning on datasets of instructions and humanwritten completions [23, 36, 13, 39]. This ‘instruction-tuning’ procedure enables LLMs to generalize to instructions outside of the instruction-tuning set and generally increase their usability [13]. Despite the success of instruction tuning, relative human judgments of response quality are often easier to collect than expert demonstrations, and thus subsequent works have fine-tuned LLMs with datasets of human preferences, improving proficiency in translation [18], summarization [38, 49], story-telling [49], and instruction-following [26, 32]. These methods first optimize a neural network reward function for compatibility with the dataset of preferences under a preference model such as the Bradley-Terry model [5], then fine-tune a language model to maximize the given reward using reinforcement learning algorithms, commonly REINFORCE [45], proximal policy optimization (PPO; [37]), or variants [32]. A closely-related line of work leverages LLMs fine-tuned for instruction following with human feedback to generate additional synthetic preference data for targeted attributes such as safety or harmlessness [2], using only weak supervision from humans in the form of a text rubric for the LLM’s annotations. These methods represent a convergence of two bodies of work: one body of work on training language models with reinforcement learning for a variety of objectives [33, 27, 46] and another body of work on general methods for learning from human preferences [12, 19]. Despite the appeal of using relative human preferences, fine-tuning large language models with reinforcement learning remains a major practical challenge; this work provides a theoretically-justified approach to optimizing relative preferences without RL.

Outside of the context of language, learning policies from preferences has been studied in both bandit and reinforcement learning settings, and several approaches have been proposed. Contextual bandit learning using preferences or rankings of actions, rather than rewards, is known as a contextual dueling bandit (CDB; [48, 14]). In the absence of absolute rewards, theoretical analysis of CDBs substitutes the notion of an optimal policy with a von Neumann winner, a policy whose expected win rate against any other policy is at least 50% [14]. However, in the CDB setting, preference labels are given online, while in learning from human preferences, we typically learn from a fixed batch of offline preference-annotated action pairs [47]. Similarly, preference-based RL (PbRL) learns from binary preferences generated by an unknown ‘scoring’ function rather than rewards [9, 35]. Various algorithms for PbRL exist, including methods that can reuse off-policy preference data, but generally involve first explicitly estimating the latent scoring function (i.e. the reward model) and subsequently optimizing it [16, 9, 12, 34, 19]. We instead present a single stage policy learning approach that directly optimizes a policy to satisfy preferences.

3 Preliminaries

We review the RLHF pipeline in Ziegler et al. (and later [38, 1, 26]). It usually includes three phases: 1) supervised fine-tuning (SFT); 2) preference sampling and reward learning; and 3) RL optimization.

SFT RLHF typically begins by fine-tuning a pre-trained LM with supervised learning on high-quality data for the downstream task(s) of interest (dialogue, summarization, etc.), to obtain a model $\pi_{\text{SFT}}$.

Reward Modelling Phase In the second phase, the SFT model is prompted with prompts $x$ to produce pairs of answers \((y_1, y_2) \sim \pi_{\text{SFT}}(y\\\|x)\). These are then presented to human labelers who express preferences for one answer, denoted as $y_w \succ y_l \mid x$ where $y_w$ and $y_l$ denote the preferred and dispreferred completion amongst $(y_1, y_2)$ respectively. The preferences are assumed to be generated by some latent reward model \(r^*(y, x)\), which we do not have access to. There are a number of approaches used to model preferences, the Bradley-Terry (BT) [5] model being a popular choice (although more general Plackett-Luce ranking models [30, 21] are also compatible with the framework if we have access to several ranked answers). The BT model stipulates that the human preference distribution $p^*$ can be written as:

\[p^*(y_1 \succ y_2 \mid x) = \frac{\exp (r^*(x, y_1))}{\exp (r^*(x, y_1)) + \exp (r^*(x, y_2))}\]

Assuming access to a static dataset of comparisons \(D = \{x^{(i)}, y^{(i)}\}_{i=1}^N\) sampled from $p^*$, we can parametrize a reward model $r_{\phi}(x, y)$ and estimate the parameters via maximum likelihood. Framing the problem as a binary classification, we have the negative log-likelihood loss:

\[\mathcal{L}\phi) = - \sum_{(x, y_w, y_l) \in D} \log \sigma(r_{\phi}(x, y_w) - r_{\phi}(x, y_l))\]

where $\sigma$ is the logistic function. In the context of LMs, the network $r_{\phi}(x, y)$ is often initialized from the SFT model $\pi_{\text{SFT}}(y\|x)$ with the addition of a linear layer on top of the final transformer layer that produces a single scalar prediction for the reward value [49]. To ensure a reward function with lower variance, prior works normalize the rewards, such that \(\mathbb{E}_{x,y \sim D} [r_{\phi}(x, y)] = 0\) for all $x$.

RL Fine-Tuning Phase During the RL phase, we use the learned reward function to provide feedback to the language model. In particular, we formulate the following optimization problem:

\[\max_{\theta} \mathbb{E}_{x \sim D, y \sim \pi_{\theta}(y\\\|x)} [r_{\phi}(x, y)] - \beta \text{KL}(\pi_{\theta}(\cdot\\\|x) \\\\| \pi_{\text{ref}}(\cdot\\\|x))\]

where $\beta$ is a parameter controlling the deviation from the base reference policy $\pi_{\text{ref}}$, namely the initial SFT model $\pi_{\text{SFT}}$. In practice, the language model policy $\pi_{\theta}$ is also initialized to $\pi_{\text{SFT}}$. The added constraint is important, as it prevents the model from deviating too far from the distribution on which the reward model is accurate, as well as maintaining the generation diversity and preventing mode-collapse to single high-reward answers. Due to the discrete nature of language generation, this objective is not differentiable and is typically optimized with reinforcement learning. The standard approach [49, 38, 1, 26] has been to construct the reward function:

\[r(x, y) = r_{\phi}(x, y) - \beta (\log \pi_{\theta}(y\\\|x) - \log \pi_{\text{ref}}(y\\\|x))\]

and maximize using PPO [37].

4 Direct Preference Optimization

Motivated by the challenges of applying reinforcement learning algorithms on large-scale problems such as fine-tuning language models, our goal is to derive a simple approach for policy optimization using preferences directly. Unlike prior RLHF methods, which learn a reward and then optimize it via RL, our approach leverages a particular choice of reward model parameterization that enables extraction of its optimal policy in closed form, without an RL training loop. As we will describe next in detail, our key insight is to leverage an analytical mapping from reward functions to optimal policies, which enables us to transform a loss function over reward functions into a loss function over policies. This change-of-variables approach avoids fitting an explicit, standalone reward model, while still optimizing under existing models of human preferences, such as the Bradley-Terry model. In essence, the policy network represents both the language model and the (implicit) reward. Deriving the DPO objective. We start with the same RL objective as prior work, Eq. 3, under a general reward function $r$. Following prior work [29, 28, 17, 15], it is straightforward to show that the optimal solution to the KL-constrained reward maximization objective in Eq. 3 takes the form:

\[\pi_r(y\\\|x) = \frac{\pi_{\text{ref}}(y\\\|x) \exp(r(x, y)/\beta)}{Z(x)}\]

where $Z(x) = \sum_y \pi_{\text{ref}}(y\|x) \exp(r(x, y)/\beta)$ is the partition function. See Appendix A.1 for a complete derivation. Even if we use the MLE estimate $r_{\phi}$ of the ground-truth reward function $r^*$, it is still expensive to estimate the partition function $Z(x)$ [17, 15], which makes this representation hard to utilize in practice. However, we can rearrange Eq. 4 to express the reward function in terms of its corresponding optimal policy $\pi_r$, the reference policy $\pi_{\text{ref}}$, and the unknown partition function $Z(\cdot)$. Specifically, we first take the logarithm of both sides of Eq. 4 and then with some algebra we obtain:

\[r(x, y) = \beta \log \left( \frac{\pi_r(y\\\|x)}{\pi_{\text{ref}}(y\\\|x)} \right) + \beta \log Z(x) \tag{5}\]

We can apply this reparameterization to the ground-truth reward \(r^*\) and corresponding optimal model \(\pi^*\). Fortunately, the Bradley-Terry model depends only on the difference of rewards between two completions, i.e., \(p^*(y_1 \succ y_2 \mid x) = \sigma(r^*(x, y_1) - r^*(x, y_2))\). Substituting the reparameterization in Eq. 5 for \(r^*(x, y)\) into the preference model Eq. 1, the partition function cancels, and we can express the human preference probability in terms of only the optimal policy \(\pi^*\) and reference policy \(\pi_{\text{ref}}\). Thus, the optimal RLHF policy \(\pi^*\) under the Bradley-Terry model satisfies the preference model:

\[p^*(y_1 \succ y_2 \mid x) = \sigma \left( \beta \log \left( \frac{\pi^*(y_1\\\|x)}{\pi_{\text{ref}}(y_1\\\|x)} \right) - \beta \log \left( \frac{\pi^*(y_2\\\|x)}{\pi_{\text{ref}}(y_2\\\|x)} \right) \right) \tag{6}\]

The derivation is in Appendix A.2. While Eq. 6 uses the Bradley-Terry model, we can similarly derive expressions under the more general Plackett-Luce models [30, 21], shown in Appendix A.3.

Now that we have the probability of human preference data in terms of the optimal policy rather than the reward model, we can formulate a maximum likelihood objective for a parametrized policy $\pi_{\theta}$. Analogous to the reward modeling approach (i.e. Eq. 2), our policy objective becomes:

\[\mathcal{L}_{\text{DPO}}( ext) = - \sum_{(x, y_w, y_l) \in D} \log \sigma \left( \beta \log \left( \frac{\pi_{\theta}(y_w\\\|x)}{\pi_{\text{ref}}(y_w\\\|x)} \right) - \beta \log \left( \frac{\pi_{\theta}(y_l\\\|x)}{\pi_{\text{ref}}(y_l\\\|x)} \right) \right)\]

This way, we fit an implicit reward using an alternative parameterization, whose optimal policy is simply $\pi_{\theta}$. Moreover, since our procedure is equivalent to fitting a reparametrized Bradley-Terry model, it enjoys certain theoretical properties, such as consistencies under suitable assumption of the preference data distribution [4]. In Section 5, we further discuss theoretical properties of DPO in relation to other works.

What does the DPO update do? For a mechanistic understanding of DPO, it is useful to analyze the Gradient of the loss function \(\mathcal{L}_{\text{DPO}}\). The Gradient with respect to the parameters $\theta$ can be written as:

\[\nabla_{\theta} \mathcal{L}_{\text{DPO}}( ext) = - \sum_{(x, y_w, y_l) \in D} \left( \frac{\partial}{\partial \theta} \log \pi_{\theta}(y_w\\\|x) - \frac{\partial}{\partial \theta} \log \pi_{\theta}(y_l\\\|x) \right) \sigma \left( \beta \left( \log \frac{\pi_{\theta}(y_w\\\|x)}{\pi_{\text{ref}}(y_w\\\|x)} - \log \frac{\pi_{\theta}(y_l\\\|x)}{\pi_{\text{ref}}(y_l\\\|x)} \right) \right)\]

where \(\hat{r}_{\theta}(x, y) = \beta \log \frac{\pi_{\theta}(y\\\|x)}{\pi_{\text{ref}}(y\\\|x)}\) is the reward implicitly defined by the language model $\pi_{\theta}$ and reference model $\pi_{\text{ref}}$ (more in Section 5). Intuitively, the Gradient of the loss function $\mathcal{L}_{\text{DPO}}$ increases the likelihood of the preferred completions $y_w$ and decreases the likelihood of dispreferred completions $y_l$. Importantly, the examples are weighed by how much higher the implicit reward model \(\hat{r}_{\theta}\) rates the dispreferred completions, scaled by $\beta$, i.e., how incorrectly the implicit reward model orders the completions, accounting for the strength of the KL constraint. Our experiments suggest the importance of this weighting, as a naïve version of this method without the weighting coefficient can cause the language model to degenerate (Appendix Table 3).

DPO outline. The general DPO pipeline is as follows:

  1. Sample completions \(y_1, y_2 \sim \pi_{\text{ref}}(\cdot \mid x)\) for every prompt \(x\), label with human preferences to construct the offline dataset of preferences \(D = \{x^{(i)}, y^{(i)}\}_{i=1,2}\).
  2. Optimize the language model \(\pi_{\theta}\) to minimize \(\mathcal{L}_{\text{DPO}}\) for the given \(\pi_{\text{ref}}\) and \(D\) and desired \(\beta\).

In practice, one would like to reuse preference datasets publicly available, rather than generating samples and gathering human preferences. Since the preference datasets are sampled using \(\pi_{\text{SFT}}\), we initialize \(\pi_{\text{ref}} = \pi_{\text{SFT}}\) whenever available. However, when \(\pi_{\text{SFT}}\) is not available, we initialize \(\pi_{\text{ref}}\) by maximizing the likelihood of preferred completions \((x, y_w)\), that \(\mathbb{E}_{x,y_w \sim D} [\log \pi(y_w \mid x)]\). This procedure helps mitigate the distribution shift, i.e., \(\pi_{\text{ref}} = \arg \max_{\pi} \mathbb{E}_{x,y_w \sim D} [\log \pi(y_w \mid x)]\), between the true reference distribution which is unavailable, and \(\pi_{\text{ref}}\) used by DPO. Further details related to the implementation and hyperparameters can be found in Appendix B.

5 Theoretical Analysis of DPO

In this section, we give further interpretation of the DPO method, provide theoretical backing, and relate advantages of DPO to issues with actor-critic algorithms used for RLHF (such as PPO [37]).

5.1 Your Language Model Is Secretly a Reward Model

DPO is able to bypass both fitting an explicit reward and performing RL to learn the policy using a single maximum likelihood objective. Note the optimization objective Eq. 5 is equivalent to a Bradley-Terry model with a reward parameterization \(r^*(x, y) = \beta \log \frac{\pi^*_{\theta}(y \mid x)}{\pi_{\text{ref}}(y \mid x)}\) and we optimize our parametric model \(\pi_{\theta}\), equivalently to the reward model optimization in Eq. 2 under the change of variables. In this section, we will build the theory behind this reparameterization, show that it does not constrain the class of learned reward models, and allows for the exact recovery of the optimal policy. We begin by defining an equivalence relation between reward functions.

Definition 1. We say that \(r(x, y) - r'(x, y) = f(x)\) for some function \(f\) if the difference between the reward functions is independent of \(y\).

It is easy to see that this is indeed an equivalence relation, which partitions the set of reward functions into classes. We can state the following two lemmas: Lemma 1. Under the Plackett-Luce, and in particular the Bradley-Terry, preference framework, two reward functions from the same class induce the same preference distribution. Lemma 2. Two reward functions from the same equivalence class induce the same optimal policy under the constrained RL problem.

The proofs are straightforward and we defer them to Appendix A.5. The first lemma is a well-known under-specification issue with the Plackett-Luce family of models [30]. Due to this under-specification, we usually have to impose additional identifiability constraints to achieve any guarantees on the MLE estimates from Eq. 2 [4]. The second lemma states that all reward functions from the same class yield the same optimal policy, hence for our final objective, we are only interested in recovering an arbitrary reward function from the optimal class. We prove the following Theorem in Appendix A.6: Theorem 1.

Under mild assumptions, all reward classes consistent with the Plackett-Luce (and Bradley-Terry in particular) models can be represented with the reparameterization \(r(x, y) = \beta \log \pi(y \mid x)\).

Proof Sketch. Consider any reward function \(r(x, y)\), which induces a corresponding optimal model \(\pi_r(y \mid x)\), specified by Eq. 4. We will show that a reward function from the equivalence class of \(r\) can be represented using the reparameterization given above. We define the projection \(f\) as:

\[f(r; \pi_{\text{ref}}, \beta)(x, y) = r(x, y) - \beta \log \left( \sum_{y'} \pi_{\text{ref}}(y' \mid x) \exp \left( \frac{r(x, y')}{\beta} \right) \right)\]

The operator \(f\) simply normalizes the reward function with the logarithm of the partition function of \(\pi_r\). Since the added normalization term is only a function of the prefix \(x\), \(f(r; \pi_{\text{ref}}, \beta)(x, y)\) is a reward function in the equivalence class of \(r(x, y)\). Finally, replacing \(r\) with the RHS of Eq. 5 (which holds for any reward function), we have:

\[f(r; \pi_{\text{ref}}, \beta)(x, y) = \beta \log \left( \frac{\pi_r(y \mid x)}{\pi_{\text{ref}}(y \mid x)} \right)\]

That is, the projection \(f\) produces a member of the equivalence class of \(r\) with the desired form, and we do not lose any generality in our reward model from the proposed reparameterization.

We can alternatively view Theorem 1 as specifying exactly which reward function within each equivalence class the DPO reparameterization selects, that is, the reward function satisfying:

\[r(x, y) = \beta \log \pi(y \mid x) + \beta \log Z(x)\]

However, following Eq. 4, we can see that Eq. 9 is the partition function of the optimal policy induced by the reward function \(r(x, y)\). The key insight of the DPO algorithm is that we can impose certain constraints on the under-constrained Plackett-Luce (and Bradley-Terry in particular) family of preference models, such that we preserve the class of representable reward models, but explicitly make the optimal policy in Eq. 4 analytically tractable for all prompts \(x\).

5.2 Instability of Actor-Critic Algorithms

We can also use our framework to diagnose instabilities with standard actor-critic algorithms used for the RLHF, such as PPO. We follow the RLHF pipeline and focus on the RL fine-tuning step outlined in Section 3. We can draw connections to the control as inference framework [20] for the constrained RL problem outlined in Section 3. We assume a parameterized model \(\pi_{\theta}(y \mid x)\) and minimize \(D_{\text{KL}}[\pi_{\theta}(y \mid x) \\| \pi^*(y \mid x)]\) where \(\pi^*\) is the optimal policy from Eq. 7 induced by the reward function \(r_{\phi}(y, x)\). With some algebra, this leads to the optimization objective:

\[\mathcal{L}_{\text{RLHF}}( ext) = -\mathbb{E}_{(x,y) \sim D} \left[ r_{\phi}(x, y) - \beta (\log \pi_{\theta}(y \mid x) - \log \pi_{\text{ref}}(y \mid x)) \right]\]

This is the same objective optimized in prior works [49, 38, 1, 26] using the DPO-equivalent reward for the reward class of \(r_{\phi}\). In this setting, we can interpret the normalization term in \(f (r_{\phi}, \pi_{\text{ref}}, \beta)\) as the soft value function of the reference policy \(\pi_{\text{ref}}\). While this term does not affect the optimal solution, without it, the policy Gradient of the objective could have high variance, making learning unstable. We can accommodate for the normalization term using a learned value function, but that can also be difficult to optimize. Alternatively, prior works have normalized rewards using a human completion baseline, essentially a single sample Monte-Carlo estimate of the normalizing term. In contrast, the DPO reparameterization yields a reward function that does not require any baselines.

Figure 2: Left. The frontier of expected reward vs KL to the reference policy. DPO provides the highest expected reward for all KL values, demonstrating the quality of the optimization. Right. TL;DR summarization win rates vs. human-written summaries, using GPT-4 as evaluator. DPO exceeds PPO’s best-case performance on summarization, while being more robust to changes in the sampling temperature.

6 Experiments

In this section, we empirically evaluate DPO’s ability to train policies directly from preferences. First, in a well-controlled text-generation setting, we ask: how efficiently does DPO trade off maximizing reward and minimizing KL-divergence with the reference policy, compared to common preference learning algorithms such as PPO? Next, we evaluate DPO’s performance on larger models and more difficult RLHF tasks, including summarization and dialogue. We find that with almost no tuning of hyperparameters, DPO tends to perform as well or better than strong baselines like RLHF with PPO as well as returning the best of N sampled trajectories under a learned reward function. Before presenting these results, we describe the experimental setup; additional details are in Appendix C.

Tasks. Our experiments explore three different open-ended text generation tasks. For all experiments, algorithms learn a policy from a dataset of preferences \(D = \{x^{(i)}, y^{(i)}\}_{i=1}^N\). In controlled sentiment generation, \(x\) is a prefix of a movie review from the IMDb dataset [22], and the policy must generate \(y\) with positive sentiment. In order to perform a controlled evaluation, for this experiment we generate preference pairs over generations using a pre-trained sentiment classifier, where \(p(\text{positive} \mid x, y_w) > p(\text{positive} \mid x, y_l)\). For SFT, we fine-tune GPT-2-large until convergence on reviews from the train split of the IMDb dataset (further details in App C.1). In summarization, \(x\) is a forum post from Reddit; the policy must generate a summary \(y\) of the main points in the post. Following prior work, we use the Reddit TL;DR summarization dataset [41] along with human preferences gathered by Stiennon et al.. We use an SFT model fine-tuned on human-written forum post summaries with the TRLX [42] framework for RLHF. The human preference dataset was gathered by Stiennon et al. on samples from a different, but similarly-trained, SFT model. Finally, in single-turn dialogue, \(x\) is a human query, which may be anything from a question about astrophysics to a request for relationship advice. A policy must produce an engaging and helpful response \(y\) to a user’s query; we use the Anthropic Helpful and Harmless dialogue dataset [1], containing 170k dialogues between a human and an automated assistant. Each transcript ends with a pair of responses generated by a large (although unknown) language model along with a preference label denoting the human-preferred response. In this setting, no pre-trained SFT model is available; we therefore fine-tune an off-the-shelf language model on only the preferred completions to form the SFT model.

Evaluation. Our experiments use two different approaches to evaluation. In order to analyze the effectiveness of each algorithm in optimizing the constrained reward maximization objective, in the controlled sentiment generation setting we evaluate each algorithm by its frontier of achieved reward and KL-divergence from the reference policy; this frontier is computable because we have acccess to the ground-truth reward function (a sentiment classifier). However, in the real world, the ground truth reward function is not known; therefore, we evaluate algorithms with their win rate against a baseline policy, using GPT-4 as a proxy for human evaluation of summary quality and response helpfulness in the summarization and single-turn dialogue settings, respectively. For summarization, we use reference summaries in the test set as the baseline; for dialogue, we use the preferred response in the test dataset as the baseline. While existing studies suggest LMs can be better automated evaluators than existing metrics [10], we conduct a human study to justify our usage of GPT-4 for evaluation in Sec. 6.4. We find GPT-4 judgments correlate strongly with humans, with human agreement with GPT-4 typically similar or higher than inter-human annotator agreement.

2 https://huggingface.co/CarperAI/openai_summarize_tldr_sft

Figure 3: Left. Win rates computed by GPT-4 for Anthropic-HH one-step dialogue; DPO is the only method that improves over chosen summaries in the Anthropic-HH test set. Right. Win rates for different sampling temperatures over the course of training. DPO’s improvement over the dataset labels is fairly stable over the course of training for different sampling temperatures.

Methods. In addition to DPO, we evaluate several existing approaches to training language models to adhere to human preferences. Most simply, we explore zero-shot prompting with GPT-J [43] in the summarization task and 2-shot prompting with Pythia-2.8B [3] in the dialogue task. In addition, we evaluate the SFT model as well as Preferred-FT, which is a model fine-tuned with supervised learning on the chosen completion \(y_w\) from either the SFT model (in controlled sentiment and summarization) or a generic LM (in single-turn dialogue). Another pseudo-supervised method is Unlikelihood [44], which simply optimizes the policy to maximize the probability assigned to \(y_w\) and minimize the probability assigned to \(y_l\); we use an optional coefficient \(\alpha \in [0, 1]\) on the ‘unlikelihood’ term. We also consider PPO [37] using a reward function learned from the preference data and PPO-GT, which is an oracle that learns from the ground truth reward function available in the controlled sentiment setting. In our sentiment experiments, we use two implementations of PPO-GT, one off-the-shelf version [42] as well as a modified version that normalizes rewards and further tunes hyperparameters to improve performance (we also use these modifications when running ‘normal’ PPO with learned rewards). Finally, we consider the Best of N baseline, sampling N responses from the SFT model (or Preferred-FT in dialogue) and returning the highest-scoring response according to a reward function learned from the preference dataset. This high-performing method decouples the quality of the reward model from the PPO optimization, but is computationally impractical even for moderate \(N\) as it requires sampling \(N\) completions for every query at test time.

6.1 How well can DPO optimize the RLHF objective?

The KL-constrained reward maximization objective used in typical RLHF algorithms balances exploitation of reward while restricting the policy from deviating far from the reference policy. Therefore, when comparing algorithms, we must take into account both reward achieved as well as the KL discrepancy; achieving slightly higher reward but with much higher KL is not necessarily desirable. Figure 2 shows the reward-KL frontier for various algorithms in the sentiment setting. We execute multiple training runs for each algorithm, using a different hyperparameter for policy conservativeness in each run (target KL \(\in \{3, 6, 9, 12\}\) for PPO, \(\beta \in \{0.05, 0.1, 1, 5\}\), \(\alpha \in \{0.05, 0.1, 0.5, 1\}\) for unlikelihood, random seeds for preferred-FT). This sweep includes 22 runs in total. After each 100 training steps until convergence, we evaluate each policy on a set of test prompts, computing the average reward under the true reward function as well as the average sequence-level KL with the reference policy \(KL (\pi \\| \pi_{\text{ref}})\). We find that DPO produces by far the most efficient frontier, achieving the highest reward while still achieving low KL. This result is particularly notable for multiple reasons. First, DPO and PPO optimize the same objective, but DPO is notably more efficient; that is, the sum of the per-timestep KL-divergences.

DPO’s reward/KL tradeoff strictly dominates PPO. Second, DPO achieves a better frontier than PPO, even when PPO can access ground truth rewards (PPO-GT).

6.2 Can DPO scale to real preference datasets?

Next, we evaluate fine-tuning performance of DPO on summarization and single-turn dialogue. For summarization, automatic evaluation metrics such as ROUGE can be poorly correlated with human preferences [38], and prior work has found that fine-tuning LMs using PPO on human preferences to provide more effective summaries. We evaluate different methods by sampling completions on the test split of TL;DR summarization dataset, and computing the average win rate against reference completions in the test set. The completions for all methods are sampled at temperatures varying from 0.0 to 1.0, and the win rates are shown in Figure 2 (right). DPO, PPO and Preferred-FT all fine-tune the same GPT-J SFT model4. We find that DPO has a win rate of approximately 61% at a temperature of 0.0, exceeding the performance of PPO at 57% at its optimal sampling temperature of 0.0. DPO also achieves a higher maximum win rate compared to the best of N baseline. We note that we did not meaningfully tune DPO’s β hyperparameter, so these results may underestimate DPO’s potential. Moreover, we find DPO to be much more robust to the sampling temperature than PPO, the performance of which can degrade to that of the base GPT-J model at high temperatures. Preferred-FT does not improve significantly over the SFT model. We also compare DPO and PPO head-to-head in human evaluations in Section 6.4, where DPO samples at temperature 0.25 were preferred 58% times over PPO samples at temperature 0.

On single-turn dialogue, we evaluate the different methods on the subset of the test split of the Anthropic HH dataset [1] with one step of human-assistant interaction. GPT-4 evaluations use the preferred completions on the test as the reference to compute the win rate for different methods. As there is no standard SFT model for this task, we start with a pre-trained Pythia-2.8B, use Preferred-FT to train a reference model on the chosen completions such that completions are within distribution of the model, and then train using DPO. We also compare against the best of 128 Preferred-FT completions (we found the Best of N baseline plateaus at 128 completions for this task; see Appendix Figure 4) and a 2-shot prompted version of the Pythia-2.8B base model, finding DPO performs as well or better for the best-performing temperatures for each method. We also evaluate an RLHF model trained with PPO on the Anthropic HH dataset 5 from a well-known source 6, but are unable to find a prompt or sampling temperature that gives performance better than the base Pythia-2.8B model. Based on our results from TL;DR and the fact that both methods optimize the same reward function, we consider Best of 128 a rough proxy for PPO-level performance. Overall, DPO is the only computationally efficient method that improves over the preferred completions in the Anthropic HH dataset, and provides similar or better performance to the computationally demanding Best of 128 baseline. Finally, Figure 3 shows that DPO converges to its best performance relatively quickly.

6.3 Generalization to a new input distribution

To further compare the performance of PPO and DPO under distribution shifts, we evaluate the PPO and DPO policies from our Reddit TL;DR summarization experiment on a different distribution, news articles in the test split of the CNN/DailyMail dataset [24], using the best sampling temperatures from TL;DR (0 and 0.25). The results are presented in Table 1. We computed the GPT-4 win rate against the ground-truth summaries in the datasets, using the same GPT4 (C) prompt we used for Reddit TL;DR, but replacing the words “forum post” with “news article”. For this new distribution, DPO continues to outperform the PPO policy by a significant margin. This experiment provides initial evidence that DPO policies can generalize similarly well to PPO policies, even though DPO does not use the additional unlabeled Reddit TL;DR prompts that PPO uses.

Table 1: GPT-4 win rates vs. ground truth summaries for out-of-distribution CNN/DailyMail input articles.

DPO PPO
0.36 0.26
0.31 0.23

4 https://huggingface.co/CarperAI/openai_summarize_tldr_sft

5 https://huggingface.co/reciprocate/ppo_hh_pythia-6B

6 https://github.com/CarperAI/trlx/tree/main/examples/hh

6.4 Validating GPT-4 judgments with human judgments

We conduct a human study to verify the reliability of GPT-4’s judgments, using the results of the TL;DR summarization experiment and two different GPT-4 prompts. The GPT-4 (S) (simple) prompt simply asks for which summary better-summarizes the important information in the post. The GPT-4 (C) (concise) prompt also asks for which summary is more concise; we evaluate this prompt because we find that GPT-4 prefers longer, more repetitive summaries than humans do with the GPT-4 (S) prompt. See Appendix C.2 for the complete prompts. We perform three comparisons, using the highest (DPO, temp. 0.25), the lowest (PPO, temp. 1.0), and a middle-performing (SFT, temp. 0.25) method with the aim of covering a diversity of sample qualities; all three methods are compared against greedilysampled PPO (its best-performing temperature). We find that with both prompts, GPT-4 tends to agree with humans about as often as humans agree with each other, suggesting that GPT-4 is a reasonable proxy for human evaluations (due to limited human raters, we only collect multiple human judgments for the DPO and PPO-1 comparisons). Overall, the GPT-4 (C) prompt generally provides win rates more representative of humans; we therefore use this prompt for the main results in Section 6.2. For additional details about the human study, including the web interface presented to raters and the list of human volunteers, see Appendix D.3.

Table 2: Comparing human and GPT-4 win rates and per-judgment agreement on TL;DR summarization samples. Humans agree with GPT-4 about as much as they agree with each other. Each experiment compares a summary from the stated method with a summary from PPO with temperature 0.

7 Discussion

Learning from preferences is a powerful, scalable framework for training capable, aligned language models. We have introduced DPO, a simple training paradigm for training language models from preferences without reinforcement learning. Rather than coercing the preference learning problem into a standard RL setting in order to use off-the-shelf RL algorithms, DPO identifies a mapping between language model policies and reward functions that enables training a language model to satisfy human preferences directly, with a simple cross-entropy loss, without reinforcement learning or loss of generality. With virtually no tuning of hyperparameters, DPO performs similarly or better than existing RLHF algorithms, including those based on PPO; DPO thus meaningfully reduces the barrier to training more language models from human preferences.

Limitations & Future Work. Our results raise several important questions for future work. How does the DPO policy generalize out of distribution, compared with learning from an explicit reward function? Our initial results suggest that DPO policies can generalize similarly to PPO-based models, but more comprehensive study is needed. For example, can training with self-labeling from the DPO policy similarly make effective use of unlabeled prompts? On another front, how does reward over-optimization manifest in the direct preference optimization setting, and is the slight decrease in performance in Figure 3-right an instance of it? Additionally, while we evaluate models up to 6B parameters, exploration of scaling DPO to state-of-the-art models orders of magnitude larger is an exciting direction for future work. Regarding evaluations, we find that the win rates computed by GPT-4 are impacted by the prompt; future work may study the best way to elicit high-quality judgments from automated systems. Finally, many possible applications of DPO exist beyond training language models from human preferences, including training generative models in other modalities.

Previous: PPO Next: Survey | Evaluating Large Language Models A Comprehensive Survey

post contain ""

    No matching posts found containing ""