DPO training guide: align LLMs with human preferences
Direct Preference Optimization (DPO) aligns language models with human preferences without needing a reward model — it's simpler and more stable than RLHF/PPO.
When to use DPO
- You have a dataset of "chosen" vs "rejected" responses
- You want to reduce hallucinations and off-topic answers
- You want alignment without the complexity of PPO
Use DPO after SFT. A typical pipeline: Pretrain → SFT → DPO.
1. DPO dataset format
[
{
"prompt": "Explain quantum entanglement.",
"chosen": "Quantum entanglement is a physical phenomenon where...",
"rejected": "Idk, something quantum."
}
]prompt, chosen and rejected may also be message lists ([{"role": "user", "content": "..."}, ...]). Since v0.76.1 every row reaches the trainer in one layout, all strings or all message lists, and a row that mixes the two in its answers is dropped at load with a reason; see Data formats.
Save as preferences.json. That one row only shows the shape of the file: Soup holds out 10% of the rows for validation by default (data.val_split), so a one-row file leaves nothing to train on. Use your real dataset.
2. Config
base: ./merged # the SFT adapter merged into its base (see below)
task: dpo
backend: transformers # root-level, NOT under training
data:
train: preferences.json
format: dpo
max_length: 2048 # sequence length lives under data
training:
epochs: 1
lr: 5.0e-7 # the key is lr, not learning_rate
batch_size: 2
gradient_accumulation_steps: 8
dpo_beta: 0.1 # the key is dpo_beta, not beta
lora:
r: 16 # LoRA turns on when r > 0; there is no enabled flag
alpha: 32An SFT run saves a LoRA adapter, not a full model, and Soup does not create a latest directory. Merge the adapter into its base first and start DPO from the merged model:
soup merge --adapter ./runs/my-sft-model --output ./mergedSpell these two exactly.
learning_rateis not the field, so it leaves you on thelrdefault of2e-5— about 40x too high for DPO, which is the difference between alignment and a wrecked model. Likewisebetais not read; the field isdpo_beta. Since v0.75.0 a misspelled key is refused when the config loads (soup trainexits 1):unknown config key 'training.learning_rate' - use training.lr. Refused.andunknown config key 'training.beta' - did you mean 'kto_beta' or 'dpo_beta'? Refused.(Since v0.77.1 a name another library uses for a Soup field, such aslearning_rate, gets ausehint; through v0.77.0 the first message readunknown config key 'training.learning_rate' - refused.) Since v0.74.0 it was at least reported; before that it was dropped in silence, which is how a 40x learning rate reaches a real run.
Key DPO hyperparameters:
dpo_beta: 0.1— KL penalty weight. Higher = stay closer to reference model.lr: 5e-7— DPO needs a much smaller LR than SFT.epochs: 1— DPO overfits quickly, rarely needs more than 1–2 epochs.
Before you train
Save the config as dpo.yaml and run soup doctor --config dpo.yaml first. Since v0.76.0 many more settings are refused when the config loads, each naming the field and what to change, so a config that loaded on an older release can stop loading. soup doctor --config prints the error and exits 2 without loading a model (it stops at the first cross-field refusal, so fix that setting and run it again until it prints no error), and since v0.77.0 it no longer prints All checks passed! above a refusal. Several things v0.76 only warned about are refused at v0.77.0, for example a staged field (validated, read by nothing) set away from its default, which stops the load with a line ending refused as of v0.77. Delete the line., and the deprecated data.remove_unused_columns: true. See Config refusals.
3. Train
soup train --config dpo.yamlIn a script or CI job, pass --yes: since v0.77.0 soup train with its stdin piped or redirected and no --yes exits 3 instead of waiting at the confirmation prompt.
During training the held-out rows (10% by default, data.val_split) are evaluated at the end of each epoch and recorded as eval_loss; training.eval_steps: N evaluates every N optimizer steps instead. That is new in v0.76.0. Upstream's changelog says that through v0.75.2 no trainer on the transformers backend scheduled an evaluation, so the held-out rows were never used and val_loss stayed empty (#1223).
4. Evaluate
Compare the DPO model against the SFT baseline:
soup eval compare <sft-run-id> <dpo-run-id>DPO variants in Soup CLI
Soup supports several preference-optimization methods — swap task: to change algorithm:
task: dpo— Direct Preference Optimizationtask: orpo— ORPO (combines SFT + DPO in one step, no reference model)task: simpo— SimPO (length-normalized, no reference model)task: ipo— IPO (IPO loss, more stable than DPO on noisy data). Since v0.77.0training.gradient_checkpointingreaches the IPO and BCO trainers, so the defaultfalsenow trains them with checkpointing off, where TRL's own default (on) used to apply; settraining.gradient_checkpointing: trueto keep the memory you had (#797, #1778)task: kto— KTO (works with unpaired binary labels). Since v0.78.0 (#2423, by @Pandiaraj-1)soup train,--dry-runincluded, refuses a KTO dataset whose rows were detected as another format before any model loads:Invalid kto dataset: train row N loaded as format 'alpaca' lacks prompt, completion or label. Use data.format: kto with kto rows.(exit 1, run on the v0.78.0 binary). Through v0.77.2--dry-runpassed, and upstream says a real run failed withKeyError: 'prompt'after the base model and LoRA had loaded. Since v0.76.0training.batch_sizemust be at least 2 on every KTO run (batch_size: autofloors at 2), not only on streamed ones (#1420). Since v0.77.0 a malformedlabelis no longer coerced (#2126): a boolean, the stringstrue/false/yes/no/1/0(case and surrounding spaces ignored) and the integers1,0and-1are read, and a null, a float such as1.0or any other value drops the row at load with a reason (KTO label must be a bool, true/false string or -1/0/1 integer, got: None).soup data validate --format ktolists the reasons for the first rows it drops and still exits 0 while any row is valid; add--min-valid-fraction 1.0to stop on one bad row
On Apple Silicon, backend: mlx trains dpo, orpo, simpo and kto natively since v0.77.0, and since v0.77.2 it runs task: preference with training.preference_loss: dpo, orpo or simpo through the same native trainer (#2333 by @vaputa; ipo, bco and preference_loss_weights blends stay refused, and the native path is covered only by the hosted macOS MLX test job, not exercised by hand before the release); each MLX preference task refuses its own list of settings at load, so see MLX backend.
SimPO has one more check. Through v0.75.2, on trl 0.29, a row whose chosen outgrows data.max_length lost its whole rejected, the length-normalised log-probability became 0/0, every LoRA tensor went NaN and the logged loss read 0.0. Since v0.76.0 task: simpo refuses such a dataset before the first step, naming how many rows are affected and the data.max_length involved (#1208). If you trained SimPO on an earlier version with long chosen answers, check the adapter. Since v0.77.0 task: simpo on the transformers backend also caps the prompt as DPO and ORPO do (#2112, #2116): after trl tokenizes a row, the prompt is cut to data.max_length // 2 tokens, keeping its end, and the answers to the room left, so no sequence exceeds data.max_length; through v0.76.1 a long prompt reached the model whole. At v0.77.1 a prompt longer than data.max_length // 2 tokens was cut even when the whole row would fit (#1185). (Since closed in v0.77.2, #1196 by @ousamabenyounes: a SimPO prompt is cut only when the row does not fit in data.max_length, then to data.max_length // 2 tokens keeping its end, with the answers getting the room left; a row that fits is unchanged, whatever its prompt length. KTO, IPO and BCO follow the same rule on the transformers backend. DPO and ORPO still cut the prompt to data.max_length // 2 tokens whether or not the row fits.) (Since closed in v0.78.0, #2555 by @Srinivasan8888: task: dpo and task: orpo on trl 0.29 also cut a prompt only when the row does not fit in data.max_length; DPO keeps the start of the prompt and ORPO the end, and native MLX DPO, ORPO and SimPO do the same, #2659 by @nazek52. The table for all six tasks is on Preference variety.)
Schedules, blends and streaming
training.dpo_beta_scheduleis wired from v0.76.0 and needsdpo_beta_end. Through v0.75.2 a run that set it ondpo,ipoorpreferencestopped at step 0, because the callback was not a Hugging FaceTrainerCallback(#1229, #1294); there is no finished run to re-check.training.dpo_ref_regen_epochsis wired under LoRA (#1345, #1636): it copies the active adapter into the frozenrefadapter every Nth epoch, and it is refused withlora.r: 0. Through v0.75.2 a run that set it ondpo,ipoorpreferencestopped when training started, for the same reason. This config loads:
training:
dpo_beta: 0.1
dpo_beta_schedule: linear
dpo_beta_end: 0.05 # required with dpo_beta_schedule
dpo_ref_regen_epochs: 2 # every 2 epochs; needs lora.r >= 1task: preferencewithpreference_loss_weightsblends DPO, IPO, SimPO and ORPO terms in one run. Since v0.77.0 adpooripoterm trains under any primary (#1785, #1828), and the reference runs once more per step; with asimpoororpoprimary,init_strategy: pissa,oloraorloftq(oruse_olora) is refused at trainer setup before the model loads, and underlora.r: 0such a term still stops at the first step;relora_stepsbeside a blend that namesdpo,ipoorbcois refused at config load, and a blend that mixesbcowith a paired loss is still refused at trainer setup. (Since closed in v0.77.0: on v0.76.0 and v0.76.1 a blend namingdpooripostopped at the first step.) See Preference Variety for the details and the re-run rows.- Resumed runs. Through v0.76.1
soup train --resumeontask: dpooripo(andtask: preferencewithdpooripo) "restored the optimizer and the step counter and trained a freshly initialised adapter" (#1768, #1797). Upstream: "Re-run any dpo, ipo or grpo training that was resumed from a checkpoint." - ReLoRA.
training.relora_stepsis refused at load since v0.77.0 ondpo,ipo,ktoandbco(and apreferencerun whose loss or blend namesdpo,ipoorbco): every ReLoRA restart merged the trained adapter into the base weights trl reads the reference from, so on v0.76.0 and v0.76.1 "from the first restart on the reference was the policy as of that step, without an error" (#1835, #1891). Removerelora_stepsand train again. - DPO also runs over a layer-streamed base (
training.stream_layers: true), and since v0.78.0 so doipoandbco; its reference is a frozenrefadapter on the same streamed base, so it needs no second copy of the base model. On an untied checkpoint such as Llama-3.1-8B,dpoandktofailed at the first backward through v0.75.2 and hold a private copy of the output head per step from v0.76.0 (bcoandipohold one too, with peak VRAM not measured for either); see Streaming preference losses. That page also explains why the memory pre-flight refuses a Llama-3.1-8B preference run on a 4 GB card.
Related
Soup is free and Apache-2.0. If it saved you a training run, starring the repo costs nothing and helps most. You can also fund the GPU time behind the work a 4 GB laptop cannot reach.