Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Direct Preference Optimization: Model Training

In the previous chapter, we built the DPO training data: each sample contains a prompt, a chosen answer, and a rejected answer. Now we use this data to perform direct preference optimization on the SFT model.

Direct preference optimization

The core idea of direct preference optimization: make the model give a higher score to the chosen answer and a lower score to the rejected answer.

Sequence log probability

How do we measure the score the model gives to an answer? We use the sequence log probability:

log⁡P(y∣x)=∑t=1Tlog⁡P(yt∣x,y<t)\log P(y|x) = \sum_{t=1}^{T} \log P(y_t | x, y_{<t})

Where:

  • xx: the prompt;

  • yy: the answer, where yty_t is the tt-th token of the answer and y<ty_{<t} are all the tokens before it;

  • TT: the number of tokens in the answer.

That is, given the prompt xx, it is the sum of the log probabilities of every token in the answer generated by the model. The larger this value, the more the model “likes” the answer.

DPO loss function

The DPO loss function is based on the log probability ratios of the policy model and the reference model:

L=−log⁡σ(β(log⁡πθ(yc∣x)πref(yc∣x)−log⁡πθ(yr∣x)πref(yr∣x)))\mathcal{L} = -\log \sigma\left(\beta \left(\log \frac{\pi_\theta(y_c|x)}{\pi_{ref}(y_c|x)} - \log \frac{\pi_\theta(y_r|x)}{\pi_{ref}(y_r|x)} \right) \right)

Where:

  • πθ\pi_\theta: the policy model being trained;

  • πref\pi_{ref}: the reference model, usually the model after SFT, whose parameters are frozen during training;

  • ycy_c: the chosen answer;

  • yry_r: the rejected answer;

  • β\beta: a coefficient that controls how far the model may deviate from the reference model;

  • σ\sigma: the Sigmoid function.

The goal of the loss function: make πθ\pi_\theta assign ycy_c a higher probability than πref\pi_{ref} does, and assign yry_r a lower probability than πref\pi_{ref} does.

Reference model

Without a reference model, the policy model may go to extremes: assigning the chosen answer an infinitely high probability and the rejected answer an infinitely low one, which degrades its ability to generate text. The reference model acts as an anchor that keeps the model from drifting too far.

Datasets

SFT dataset

The same SFT dataset SFTDataset as in Chapter 16. The DPO dataset extends it.

DPO dataset

The DPO dataset DPODataset inherits from the SFT dataset and processes (prompt, chosen answer, rejected answer) triples:

  • split each triple into two: (prompt, chosen answer) and (prompt, rejected answer);

  • encode each of the two groups into features and labels, and add a mask;

  • return a six-element tuple: (chosen features, chosen labels, chosen mask, rejected features, rejected labels, rejected mask).

Loss function

DPO binary cross-entropy loss function

The DPO loss function DPOLoss implements the loss above, which is the binary cross-entropy after applying the Sigmoid to the margin:

  • Compute the differences:

pdiff=policychosen−policyrejectedp_{diff} = policy_{chosen} - policy_{rejected}
rdiff=referencechosen−referencerejectedr_{diff} = reference_{chosen} - reference_{rejected}
  • Compute the margin:

margin=β⋅(pdiff−rdiff)margin = \beta \cdot (p_{diff} - r_{diff})
  • Sigmoid:

sigmoid=11+e−marginsigmoid = \frac{1}{1 + e^{- margin}}
  • Loss: return the mean of −log⁡(sigmoid)-\log(sigmoid).

Where:

  • policychosenpolicy_{chosen}, policyrejectedpolicy_{rejected}: the sequence log probabilities that the policy model gives to the chosen and rejected answers;

  • referencechosenreference_{chosen}, referencerejectedreference_{rejected}: the sequence log probabilities that the reference model gives to the chosen and rejected answers;

  • β\beta: a coefficient, corresponding to beta in the code, with a default value of 0.1.

Trainer

DPO trainer

The DPO trainer DPOTrainer also inherits from the GPT trainer GPTTrainer. The main differences are:

  • Two models: besides the model being trained, model, the DPO trainer also has a reference model, reference. The parameters of the reference model are frozen and do not take part in training;

  • _sequence_log_prob (sequence log probability function): computes the model’s log probability for each (features, labels, mask) group, counting only the positions where the mask is 1;

  • train (training function): computes the scores that the policy model and the reference model give to the chosen and rejected answers, and passes them to the DPO loss function.

💡 Tip: The reference model and the policy model have identical parameters at the start of training. During training, the policy model’s parameters keep being updated while the reference model’s parameters stay unchanged, serving as a control group. Note that the policy model is in training mode (dropout enabled) while the reference model is in inference mode (dropout disabled), so even with identical parameters, the scores they give are not exactly the same.

Hyperparameters

Learning rate

The preference optimization stage usually uses a smaller learning rate than the SFT stage. This chapter uses 0.000001, one hundredth of that in the SFT stage.

Model parameters

The other model parameters must stay the same as in the pre-training stage.

Modeling

Loading the models

Create two models:

  • model: the policy model;

  • reference: the reference model.

Both models load the SFT model parameters.

Loading the DPO data

Training

epoch 1 step 100/460 loss 0.6913 lr 0.000001
epoch 1 step 200/460 loss 0.6926 lr 0.000001
epoch 1 step 300/460 loss 0.6761 lr 0.000000
epoch 1 step 400/460 loss 0.6767 lr 0.000000
epoch 1 saved DPO model to ../../../../data/tinyshakespeare-dpo.npz

Inference

ROMEO:

HORTENSIO:
Villor, will I come: did a hear,
Not our drow supposessiance, that you married haste,
Like a joy a Jack for joy her.

First Servingman:
I do go of year.

PITONES:
Hereford thy country.

PRUTUS:
Call now.

CoRLIFFORD:

SICINIAN:

BRUTUS:

IS:
N

In this chapter, we trained the SFT model with direct preference optimization on the DPO dataset: the model is made to give a higher score to the chosen answer and a lower score to the rejected answer, and the reference model acts as an anchor that keeps the model from drifting too far.

The training loss fluctuated between 0.68 and 0.72 without a clear decrease. When the policy model and the reference model give exactly the same scores, the loss is exactly ln⁡2≈0.693\ln 2 \approx 0.693, so this indicates that the trained model changed little relative to the reference model. Our focus is to understand the DPO workflow; with such a small teaching model, we should not expect a clear effect.

With this, we have completed model fine-tuning, step by step teaching the pre-trained model to converse effectively with users:

  • SFT (supervised fine-tuning): teaches the model to answer questions;

  • DPO (direct preference optimization): teaches the model to answer questions reasonably.

Exercises

  1. Try changing the beta parameter of the DPO loss function from 0.1 to 0.5 or 0.01 and observe how the training result changes. What does the beta parameter control?

  2. Try raising the learning rate to 0.00001 or 0.0001 and observe how the training loss changes.