DPO from scratch and its diagnostics
Implement DPO with masked sequence log-probabilities, a precomputed reference to save memory, beta-scaled loss, and implicit reward metrics. Sweep beta, monitor chosen and rejected log-probabilities for likelihood displacement, and compare the resulting policy with SFT and best-of-n.
After this lesson you can
- Derive DPO loss from the KL-regularized RLHF objective.
- Implement sequence log-probabilities, a precomputed reference, and DPO loss.
- Sweep beta and record margins, log-probabilities, and length.
- Evaluate win rate against SFT and domain performance with intervals.
Before you start
- P08On-policy preference generationBest-of-n baselineLoRA from scratch
- 20KL-regularized RLHF objectiveDirect Preference OptimizationImplicit rewardLikelihood displacementDPO gradient weightingIdentity Preference OptimizationReference-free preference optimization
- 07KL-regularized optimization
- 06Lagrange multipliers
A comparison does not say how much each answer increases
The previous lesson built pairs for the same prompt: a chosen and a rejected answer. Now we want to fit the policy directly to those pairs without first training a scalar reward model. This is direct preference optimization (DPO). The comparison requires only that the chosen answer improve relative to the rejected one. It does not guarantee that the chosen answer’s absolute probability rises. First examine a counterexample with three possible answers.
In this family, the chosen logit minus the rejected logit is , while normalization includes the third answer. The uniform reference gives both equal log-probabilities, so the implicit margin is . If the third answer grows fast enough, both probabilities can fall even as their ratio rises. Moving changes the displayed margin’s scale; it does not simulate the effect of on training. Diagnosing an actual run requires saving both log-probabilities, lengths, and external evaluation, not just loss.
The regularized problem and its solution
For a fixed prompt , reference distribution supported on the allowed answers, reward , and , consider
Assume a finite answer space and for all answers. Define . The optimal policy is
To verify this without hiding a multiplier, substitute the expression into . The objective becomes , which is maximized when . Solving for gives . The normalization term depends on the prompt, not the answer, and cancels when comparing two answers to the same prompt.
The support requirement explains what happens to answers the reference declares impossible. If and the policy assigns them positive mass, the forward KL is infinite; with a positive penalty such policies are excluded from the finite solution. The formula applies on the reference’s effective support, but says nothing about answers outside it. In autoregressive models with exact softmax every token has positive probability, though sampling truncation and external constraints can change the support of the distribution actually observed.
Adding a constant shared by all answers to a prompt does not change the optimal policy either: it multiplies all numerator terms by the same factor, which cancels in . Bradley-Terry comparison has the same invariance because it uses differences. The derivation therefore identifies a family of equivalent rewards per prompt. Do not infer a shared absolute utility level across different tasks or prompts from the loss.
If preferences follow Bradley-Terry, the resulting negative log-likelihood loss is
This is the parameterization of Rafailov and colleagues. The identity describes the regularized problem’s optimum under its assumptions; training a finite network on limited data does not guarantee reaching that optimum or improving external tasks. Coefficient appears in both the regularized problem and the loss, but its practical effect also depends on the optimizer and training duration.
To understand each pair’s weight, write . The derivative of loss with respect to is . A pair with a strongly negative margin has weight near one; with a large positive margin its weight approaches zero. The derivative with respect to log-probabilities also carries factor and opposite signs for chosen and rejected answers. In a shared network those outputs are not independent parameters: the same weight change alters other answers and each distribution’s denominator.
Interpreting the margin requires retaining the reference. Suppose the policy assigns chosen and rejected answers probabilities 0.20 and 0.10, and the reference assigns them 0.40 and 0.10. The policy’s chosen-to-rejected ratio is two; the reference ratio would also be two only if its probabilities were 0.20 and 0.10. With the stated reference its ratio is four: the relative change favors the rejected answer even though the chosen one remains more probable in absolute terms. DPO compares both ratios, not just the ordering of policy probabilities. With the margin is , approximately .
This comparison does not produce a universal utility scale. The implicit quantity can have a prompt-dependent constant added without changing the pair preference. Do not compare absolute values across prompts as if they shared a scoring rule without further calibration. Nor should this scalar be confused with the probability an answer is correct: under the Bradley-Terry preference model, its probability comes from applying a sigmoid to a difference in rewards.
The closed-form optimum also clarifies the role of . For a fixed reward and full-support reference, as grows the ratios approach each other and the optimal policy approaches the reference. As decreases, mass concentrates on maximum-reward answers; if there are several maxima, the reference determines their relative shares in the limit. This is a property of the ideal fixed-reward problem. In practical training reward is not directly observed, multiplies the margin, and learning rate, data, and fitting time interact with it, so a quality curve cannot be predicted from the mathematical limit alone.
The Bradley-Terry assumption also deserves scrutiny. Noisy preferences, ties, and disagreements between judges do not become a single truth by applying a formula. Keep ties separate and do not train on identical answers as though one were better. When a judge changes its mind after reversing order, that discrepancy is information about the measuring instrument.
A verifier preference in this project has narrower scope than a general human preference. A pair is labeled by whether its identifier belongs to a valid CWE set and meets a strict format contract; it does not assess any additional explanation. If the candidate distribution changes during fitting, the policy may produce errors scarcely represented in the original pairs. The preference set describes answers sampled by SFT under specific conditions. Examining new outputs and keeping external evaluation help detect that distribution shift, while reusing test labels to select another configuration would introduce leakage.
Alternatives change the problem as well as the function name. Azar and colleagues study a framework of preference objectives and propose IPO as one choice; their illustrative results do not guarantee it outperforms DPO on CWE. In optimization without an explicit reference, removing or replacing the reference term changes which deviations are penalized. When comparing such a variant with DPO, do not attribute every difference solely to memory cost: the objective has changed too.
Shifting and the reference
Precomputing reference log-probabilities calculates per-answer sums once using the frozen SFT policy, avoiding two model copies on the GPU during fitting. Store with each sum the hashes of the reference checkpoint, tokenizer, template, truncation, and mask: changing any invalidates the cache. The policy is initialized from that same reference, but the data can come from another policy if declared. It is not a mathematical identity that every pair must have been sampled by the reference.
For a token sequence , the logit at position predicts . Sum only answer tokens, including end-of-turn if required by the protocol, and exclude the prompt and padding. A mask shifted one position can train a different function without a shape error. If an answer is truncated, apply exactly the same rule to policy and reference, and record how many pairs are discarded.
A silent failure occurs when a sum is stored without its boundary. For example, two tokenizers might encode the space between the assistant header and first word differently. If the boundary is calculated in characters but loss applies to tokens, the first answer prediction can be omitted or the final prompt token included. A defensible check constructs the prefix and complete dialogue with the real template, verifies that the tokenized prefix matches the beginning of the full sequence, and only then builds the mask. If this property fails, inspect the boundary; guessing the length is insufficient.
The cache is a derived artifact, not an independent source of truth. If the SFT adapter is updated, an answer changed, or the end token changes, its sums no longer match the new input. Include a fingerprint of the pair set and tokenized IDs alongside the adapter files and configuration. Recomputing the reference on a sample and comparing each sum helps detect write or read errors. For long-running work, record completed pairs and validate their identity on resume; a partial cache must not be mistaken for a complete one.
Local lab: preference sweep
Keep the p08-l04 SFT directory and samples_train.json generated in p08-l05; the latter is the answer set, not the reward adapter. Download dpo.py and use your own output directory. The program needs the same revision and CUDA environment described in p08-l05, with the base cached. Set the paths and run it, for example in PowerShell:
$env:P08_L04_DIR = 'C:\ruta\a\salida-p08-l04'
$env:P08_PREFERENCES_DIR = 'C:\ruta\a\preferencias'
$env:P08_DPO_DIR = 'C:\ruta\a\dpo'
python dpo.py
The program first computes and saves the reference for training and validation, then trains one epoch for each of 0.05, 0.1, and 0.5. It records diagnostics and checkpoints with optimizer and random states every 50 steps and at the end. If an interruption leaves an incomplete JSON line, inspect the partial output before resuming; do not treat it as a complete cache. Retain all three beta-*.json files and their adapters. This lesson’s panel accepts a run’s JSON to inspect trajectories and change against SFT on development data; select the configuration on development data before opening the final test.
To compare the selected variant with an automatic judge, also download juez.py. The program reads snapshot sft-dev.json, the selected variant’s result, and dev.json; it checks their hashes and order before sending pairs. This run selected beta-0.5.json; if your sweep chooses another beta, use its corresponding file. The local server must provide the API compatible with /v1/chat/completions and Qwen2.5-7B-Instruct GGUF Q4_K_M at revision bb5d59e06d9551d752d08b292a50eb208b07ab1f, using the alias recorded by the script. For example:
python juez.py --baseline "$env:P08_DPO_DIR\sft-dev.json" --result "$env:P08_DPO_DIR\beta-0.5.json" --dev "$env:P08_L04_DIR\dev.json" --out 'C:\ruta\a\juez-desarrollo'
The judge presents differing answers in both orders, retains the raw response, and leaves invalid or contradictory outputs unresolved; identical answers count as ties. The interval resamples complete components and excludes unresolved comparisons. Checking the alias detects a different declared identity but does not cryptographically verify weights loaded by a server, so retain hashes of both shards and server provenance. This post-selection judgment describes development data and does not replace test evaluation or human annotation.
The next example uses a two-token vocabulary and two predictions. The first supervised target is token 1, predicted by the first logit vector; the second is token 0, predicted by the second. The mask aligns with the targets, not the logits predicting them.
import numpy as np
logits = np.array([[0., 2.], [3., 0.], [0., 0.]])
labels = np.array([-100, 1, 0])
mask = np.array([0, 1, 1], dtype=bool)
z = logits[:-1]
normalizer = np.logaddexp(z[:, 0], z[:, 1])
targets = labels[1:]
selected = z[np.arange(len(targets)), targets] - normalizer
print('log-probabilidades de los tokens de respuesta:', np.round(selected[mask[1:]], 6))
print('suma de la respuesta:', selected[mask[1:]].sum())The sum is approximately : the two contributions are and . This is the sequence log-probability under the toy model, not a per-token mean. The reference must use the same convention before subtracting its log-probabilities from the policy’s.
The following check isolates the DPOTrainer loss from TRL 1.19.0 with a fixed batch of log-probabilities. Use the previous lesson’s local environment with PyTorch and TRL 1.19.0. The test model returns those values without training weights; it detects sign, half-ordering, and precomputed-reference errors before time is invested in the real experiment. _compute_loss is an internal API and may change between versions, so the cell requires the specific version.
import importlib.metadata
from collections import defaultdict
from types import SimpleNamespace
import torch
import torch.nn.functional as F
from trl import DPOTrainer
if importlib.metadata.version('trl') != '1.19.0':
raise RuntimeError('Esta comprobación usa TRL 1.19.0')
class IdentityAccelerator:
device = torch.device('cpu')
def gather(self, value): return value
def gather_for_metrics(self, value): return value
class Fixed(torch.nn.Module):
def forward(self, **inputs):
logps = torch.tensor([[-0.4, -0.6], [-0.8, -1.2], [-1.0, -2.0], [-1.5, -2.5]], dtype=torch.float64)
zeros = torch.zeros_like(logps)
return SimpleNamespace(log_probs=logps, entropy=zeros, mean_logits=zeros,
is_top1=torch.zeros_like(logps, dtype=torch.bool))
model = Fixed().eval()
trainer = DPOTrainer.__new__(DPOTrainer)
trainer.model = model
trainer.accelerator = IdentityAccelerator()
trainer.aux_loss_enabled = False
trainer.ld_alpha = None
trainer.precompute_ref_logps = True
trainer.f_divergence_type = 'reverse_kl'
trainer.loss_types, trainer.loss_weights = ['sigmoid'], [1.0]
trainer.beta, trainer.use_weighting = 0.1, False
trainer._metrics = {'train': defaultdict(list), 'eval': defaultdict(list)}
trainer._total_train_tokens = 0
inputs = {'input_ids': torch.tensor([[0, 1, 2]] * 4), 'attention_mask': torch.ones(4, 3, dtype=torch.long),
'completion_mask': torch.tensor([[0, 1, 1]] * 4),
'ref_chosen_logps': torch.tensor([-3., -4.], dtype=torch.float64),
'ref_rejected_logps': torch.tensor([-3., -4.], dtype=torch.float64)}
actual = trainer._compute_loss(model, inputs, False)
own = F.softplus(-0.1 * torch.tensor([2., 2.], dtype=torch.float64)).mean()
print('TRL:', actual.item(), '· propia:', own.item(), '· diferencia:', abs(actual.item() - own.item()))
assert torch.allclose(actual, own, atol=1e-5, rtol=0)npm run lab and open the connection link.Both losses are approximately 0.598139 on this batch. Agreement here does not establish that masking, caching, and complete training are correct: those checks must use the real pairs and checkpoint.
What a beta sweep compares
A useful comparison starts before fitting. Fix the training-pair set, hold out complete CWE components for development, and freeze both the SFT reference and tokenizer. For each value, start from the same adapter and use the same data order, update count, and truncation rule. A development difference then describes the experimental decisions with a different beta; it does not automatically attribute the outcome to one abstract property of regularization. Keep the test set closed until selecting the variant using a prespecified rule.
The splitting unit matters. Multiple advisories may come from the same catalog component, and the same text can have multiple valid labels. Randomly splitting rows could place near-identical patterns in training and validation. A component split keeps its rows together. The verifier must recognize all labels allowed by the catalog and record the proportion of prompts yielding at least one chosen and one rejected answer. A prompt whose candidates all have the same preference label supplies no contrast; excluding it when forming pairs also changes the population reaching DPO.
Check the initial state. If policy and reference are identical, every log-ratio and the margin are zero, and per-pair loss is , apart from changes caused by precision, masking, or tokenization. A different value can indicate different checkpoints, a cache from another version, or sums over different tokens. This check alone does not prove the objective correct: an identical but incorrect mask on both sides can also give zero initially.
Another useful check before loading a large model uses small logits you can calculate by hand and two answers of different lengths. Compare your sum with a direct token-by-token sum, including an end token and a padding position. Then change only the padding and check that the valid result is unchanged. Such a test detects shifting and masking errors but does not guarantee the real template has the expected boundary. Therefore test the pinned tokenizer as well as the small numerical example.
A comparison with a library must also state what was matched. Construct a fixed batch of policy and reference log-probabilities and pass the same values to both losses, as in the previous cell. Agreement within reasonable numerical tolerance validates signs and reduction for that batch. Comparing training also requires matching initialization, optimizer, pair order, seed, precision, and dropout handling. Different curves do not identify a loss error if any factor changes; equal losses at the first step do not establish equal later gradients.
Pair count is not the number of independent examples. Answers are reused to create multiple comparisons for one advisory, and some advisories share a component. Shuffling pairs before splitting can put a nearly identical answer on both sides. Assign components first, then construct pairs within each split. Record coverage: an advisory producing only correct or only incorrect answers under the verifier forms no contrastive pair even though it belongs to the original set. DPO trains on the retained population, and external evaluation should also cover advisories without a training pair.
For the candidates in p08-l05, the rule yields 1532 training rows and 404 validation rows, but only 412 and 109 distinct combinations of identifier, component, chosen answer, and rejected answer respectively. Other rows repeat textually identical comparisons because sampling produced repeated answers. No row compares an answer with itself, and split components do not overlap. Retaining repetitions gives more weight to frequently occurring comparisons: describe this procedure and do not present 1936 rows as independent observations. Deduplication changes that weighting and must be declared as another experiment. Development intervals resample whole components, not pair rows.
For this comparison SFT was reloaded with eval() and its baseline measured in batches of 16: 94 correct out of 117 development advisories. An earlier measurement during adapter regeneration gave 95 of 117, but left training mode with dropout enabled and used batches of 32. It is not an equivalent inference baseline, and simultaneous changes do not permit assigning the difference to one cause. The sweep compares each variant with SFT measured under its protocol; final testing must use the same mode, batch size, and extractor for all variants.
Choosing among SFT, best-of-n, and DPO requires a comparable budget. Best-of-n can spend generations per prompt and one scoring pass per answer; DPO pays an upfront fitting cost and then generates one answer per query. For a given workload, report training cost, per-query cost, latency, and verifiable quality. There is no single winner without specifying the expected query count and acceptable degradation. A judge advantage can guide inspection, but display the domain metric and its interval alongside it.
During fitting, periodically record loss and margin on the same validation-pair set, not different batches. Add each answer’s log-probability separately and its token length. Falling training loss with stable or rising development loss is a signal to investigate overfitting; alone it does not establish that the overall policy worsened. Long-sequence probabilities tend to be smaller by construction, so also inspect results by length without silently changing the sum defining the loss.
In an actual run with and 383 updates, mean chosen log-probability changed from -0.717 to -0.846 and rejected from -1.562 to -6.774 across 404 validation rows; mean margin rose from 0 to 0.254. Both log-probabilities fell despite the margin increase. These are means over rows with repetitions, not independent tests or a guarantee that every answer behaves this way. The full result preserves curves and provenance.
On the same 117 development advisories, the SFT baseline got 94 correct and this variant got 91. The DPO-minus-SFT difference was -2.56 percentage points, with 95% component bootstrap interval [-7.76, 2.59]; the interval includes zero. The original run did not separately retain each reference SFT answer. A later rerun obtained 94/117 and exactly reconstructed the difference and interval, but cannot establish that every answer matched the original. This comparison uses greedy generation and is not a judge win rate. In p08-l05, best-of-16 reached approximately 59.8% on the same advisories with sampled candidates; different procedures prevent attributing the observed gap solely to the fitting method.
With , another epoch produced 90 correct of 117 versus 94 for SFT measured in that run. The paired difference was -3.42 percentage points, with 95% component interval [-8.62, 1.71], also including zero. The variant JSON retains diagnostics; neither comparison replaces the decision on the full sweep or judge evaluation.
With , the variant got 92 of 117 versus 94 for SFT: difference -1.71 points, 95% interval [-6.90, 3.42]. The full result includes the retained baseline’s hash. The rule fixed before examining the test chooses the largest development difference, breaking ties by smaller beta; it therefore selects 0.5 in this sweep. None of the three intervals excludes zero: choosing a configuration does not prove improvement over SFT or correct selection uncertainty. The judge and final test separately evaluate the selected adapter.
The automatic 7B judge then compared SFT with the selected variant on the same 117 development advisories. Answers were identical in 105 cases. Of the remaining 12, five favored DPO and one favored SFT in both orders; the other six changed winner on reversal and remained unresolved. Among 111 resolved cases, counting ties as half wins, DPO’s rate was 51.8%, with component bootstrap interval [50.0%, 54.1%]. The lower end reaches 50%, so a win is not established. Counting all six unresolved cases as DPO losses or all as wins gives a rate between 49.1% and 54.3% over 117 advisories; these are sensitivity bounds, not a confidence interval.
The CWE verifier distinguished correct from incorrect in only five resolved non-tie comparisons; the judge agreed in two. This sample is too small to characterize reliability. The full judge log retains both orders and responses; its provenance identifies weights, server, time, and observed resources. The same quantized 7B model was served on CPU with four threads in one instance. These are not human labels or an independent test, because the advisories were already used to select beta. The held-out final evaluation has a different role.
To compare final policies, use the same prompts and retain both outputs. On CWE the SFT lesson’s extractor can measure the same task, without confusing it with the stricter preference-labeling criterion. Per-prompt differences allow paired intervals; if a component has several rows, resample components rather than treating them as independent observations. One possible selection rule, fixed before looking at test data, maximizes development accuracy difference and breaks ties by smaller beta. With three betas and multiple diagnostics, patterns found after inspecting the full panel are exploratory and need independent confirmation.
DPO diagnostics separate the margin from both log-probabilities, length, and the external metric. If both fall but the rejected one falls more, margin rises and loss falls; that does not prove the chosen answer became more probable. If answers lengthen, also compare token counts and results by length; do not automatically conclude that length caused an improvement. For an estimate outside development, use held-out prompts, control position through random or both orders, and calculate a paired interval with appropriate grouping.
import numpy as np
beta, chosen_ratio, rejected_ratio = 0.1, 2.0, 0.5
margin = beta * (chosen_ratio - rejected_ratio)
print('margen:', margin, 'pérdida:', np.logaddexp(0, -margin))Exercises
import numpy as np
def sequence_logprobs(logits, labels, mask):
...
def dpo_loss(pi_c, pi_r, ref_c, ref_r, beta):
...Step 1 of 2. Which distribution turns the objective into a constant minus a KL?