# Quickstart: Preference Fine-Tuning (DPO)

Source: https://docs.surogate.ai/engine/getting-started/quickstart-dpo/

This quickstart runs an offline **Direct Preference Optimization** job. DPO teaches a model to
prefer a *chosen* response over a *rejected* one for the same prompt. It learns from the pairs
directly, with no reward model and no rollouts. You supply a static dataset of `{prompt, chosen,
rejected}` triples and run a single command.

## 1) Prepare preference data

A `type: preference` dataset has three required fields per row. `prompt` can be a
string or a chat `messages` list, and `chosen`/`rejected` are the two competing assistant
continuations. Chat rows may also set `enable_thinking`:

```json
{"prompt": "Scrie corect în limba română.", "chosen": "Ei mergeau acasă.", "rejected": "Ei mergerăm acasă."}
```

Preference data loads through the same [dataset pipeline](/engine/guides/datasets/) as the other
dataset types (`text`, `instruction`, `conversation`): `path` may be a local JSONL/JSON/parquet/CSV
file, a dataset directory, or a HuggingFace hub repo, and `subset`/`split`/`samples`
work as usual. If your columns have other names, map them with `prompt_field`,
`chosen_field`, and `rejected_field` (see the
[config reference](/engine/reference/config/#preference-dataset-options-type-preference)).

The loss covers only the response tokens. Minimal pairs, where `chosen` and
`rejected` differ by as little as a single word, give the cleanest signal: the model
learns the preferred token instead of incidental differences in style or length.

## 2) Write a config

```yaml
# dpo.yaml
model: ./path/to/start_checkpoint        # the model to fine-tune (also the DPO reference)
output_dir: ./out_dpo

lora: true
lora_rank: 16
lora_alpha: 32
lora_target_modules: [q_proj, k_proj, v_proj, o_proj, gate_proj, up_proj, down_proj]

recipe: fp8-hybrid
optimizer: adamw_8bit
learning_rate: 5.0e-7
lr_scheduler_type: constant
gpus: 1
per_device_train_batch_size: 8           # must be even — each pair is 2 rows (B/2 pairs/step)
gradient_accumulation_steps: 1
sequence_len: 1024
max_steps: 80
save_steps: 20

loss:
  type: dpo
  dpo_beta: 0.1                           # KL temperature; higher pushes harder from the reference
  length_norm: false                      # enable when chosen/rejected lengths differ a lot
  span_mask: false                        # score only disjoint differing token spans
  reference_free: false                  # optimize the absolute chosen/rejected gap
  target_margin: 0.0                     # requires reference_free; beta-scaled target gap

datasets:
  - path: ./pairs.jsonl
    type: preference
```

DPO inherits all SFT settings (LoRA, recipe, optimizer, schedule, checkpoint resume
and retention). The base model is frozen and only the LoRA adapter is trained. In
standard DPO, the **reference** is the frozen start checkpoint, evaluated inline on
the same micro-batch as the policy. This keeps FP8 activation scaling aligned with
the policy forward. `reference_free: true` skips that extra reference forward. The
`loss:` keys are listed under [DPO Settings](/engine/reference/config/#dpo-settings).

## 3) Run

```bash
CUDA_VISIBLE_DEVICES=0 surogate dpo dpo.yaml
```

For multiple GPUs, set `gpus: N`. Surogate shards distinct pairs across the GPUs
(data-parallel) and averages the gradients. The [`dpo` command](/engine/reference/cli/#dpo) lists its options.

## 4) What to expect

```
step=0 dpo_loss=0.6931 acc=0.000 margin=0.0000 ...
step=1 dpo_loss=0.6871 acc=1.000 margin=0.0121 ...
```

- **Step 0** logs `dpo_loss ≈ 0.6931 = log 2` with `margin = 0`. This is your sanity
  check: at initialization the policy equals the reference (LoRA `B` is zero-init), so
  the preference margin is exactly zero. If step 0 does not show ~0.693, something
  is wrong with the reference or the data layout.
- As training proceeds, `dpo_loss` decreases, `margin` goes positive, and `acc`
  (fraction of pairs with `margin > 0`) rises toward 1.0.

## 5) Outputs

- `output_dir/step_{:08}/adapter_model.safetensors`: LoRA checkpoints at `save_steps`;
  older checkpoints are removed according to `save_total_limit`.
- `output_dir/final_adapter/`: the final LoRA adapter.

Merge an adapter into a standalone model with [`surogate merge`](/engine/reference/cli/#merge):

```bash
surogate merge --base-model ./path/to/start_checkpoint \
  --checkpoint-dir ./out_dpo/step_00000040 --output ./out_dpo_eval
```

To serve it quantized, turn the merged checkpoint into a GGUF first (see [Serving models](/engine/inference/serving-models/)):

```bash
surogate quantize --model ./out_dpo_eval --output ./out_dpo_eval-Q4_K_M.gguf --type q4_k_m
surogate serve ./out_dpo_eval-Q4_K_M.gguf --port 8080
```

## Tips

- **`dpo_beta`** is the main knob. Too high overfits the preference (and can hurt
  general quality); too low barely moves the model. `0.1` is a good place to start.
- **Build minimal pairs.** Broad, full-rewrite pairs leak style and length. Prefer pairs
  that isolate the exact behavior you want to change.
- **Small learning rate.** The preference gradient is small, so `gradient_dtype` and
  the trainable LoRA weights use FP32 to keep it from being lost to BF16 rounding. The
  frozen base does not get a wasteful FP32 master copy.

## See also

- [Training Modes](/engine/getting-started/training-modes/): when DPO is the right choice and when SFT or GRPO fits better
- [Quickstart: GRPO](/engine/getting-started/quickstart-grpo/): online RL, for when you have a reward signal instead of fixed pairs
- [Config reference](/engine/reference/config/): every DPO and SFT key
- [CLI reference](/engine/reference/cli/): all `surogate` commands
