# Preference training (DPO)

Source: https://docs.surogate.ai/engine/examples/recipes/dpo/

<!-- From examples/dpo/README.md in the engine repo; configs and scripts it names are linked on GitHub. -->
DPO trains a model to prefer one answer over another from pairs of examples.
[qwen3.yaml](https://github.com/invergent-ai/surogate/blob/main/examples/dpo/qwen3.yaml) teaches Qwen3-0.6B to prefer corrected grammar from the
eight local [pairs](https://github.com/invergent-ai/surogate/blob/main/examples/dpo/pairs.jsonl). These rows show the format; they are far too few
for a production fine-tune.

```bash
surogate dpo examples/dpo/qwen3.yaml
```

The reference is the frozen starting policy, evaluated inline. Only the adapter
trains, and its weights and gradients use FP32 so the small preference signal isn't
lost. Each pair takes two rows, so `per_device_train_batch_size` must be even.
`span_mask: true` limits the loss to the token spans that differ in these minimal
pairs. DPO packs pairs itself, so generic SFT packing is disabled.

To try reference-free preference training, copy this config, choose a different
output directory and replace its `loss` block with:

```yaml
loss:
  type: dpo
  dpo_beta: 0.1
  reference_free: true
  target_margin: 1.0
  length_norm: true
  span_mask: false
```

This skips the reference forward pass and optimizes a length-normalized likelihood
gap. `target_margin` requires `reference_free: true`. Length normalization helps
when your real chosen and rejected answers differ a lot in length.

Data can come from JSONL, JSON, CSV, parquet or a Hugging Face dataset. Map custom
columns with `prompt_field`, `chosen_field`, `rejected_field`, and optionally
`enable_thinking_field` (see the [preference format](/engine/guides/datasets/)).
A prompt may be text or chat messages. Replace the tiny fixture with real preferences
before you run longer.

DPO saves periodic `step_XXXXXXXX` checkpoints and a `final_adapter` directory. To
merge the adapter and serve the result:

```bash
surogate merge --base-model Qwen/Qwen3-0.6B \
  --checkpoint-dir ./outputs/dpo/qwen3/final_adapter --output ./outputs/dpo/merged
surogate serve ./outputs/dpo/merged
```

Next: the [DPO quickstart](/engine/getting-started/quickstart-dpo/) walks through a run step by step and explains the loss options.
