REAL PYTORCH · CPU TRAINING AND AUTOGRAD

Differentiate response-masked Direct Preference Optimization

Inputs are finite floating [batch,2,time,vocab] logits and int64 [batch,2,time] aligned response targets; pair index 0 is chosen, 1 rejected, and -100 masks non-response positions. Sum valid token log probabilities for each response, not their length average. Return mean(softplus(-beta*((policy_chosen-policy_rejected)-(reference_chosen-reference_rejected)))). Detach all reference logits. Every response needs a valid target. Reject bad labels, shape, empty batches and nonpositive/nonfinite beta. This is the DPO objective, not a claim of aligned behavior from passing a small fixture.

Run this Lab in Pythilo

Open Labs, choose its topic and tap Download entire topic, or Download entire category for all its Labs, including the required Python packages, then load the starter or worked answer and tap Trace. Progress, pause, resume and removal are in Downloads. Independent checks execute real CPU training and gradients.

No GPU, external model weights or API key is required. After downloading the topic and packages, this Lab runs offline.

PyTorch is unavailable in this browser runtime. The code and lessons are readable here; execution and checks run in the app.

Pythilo on the App Store →

Read lesson: Differentiate response-masked Direct Preference Optimization →

Your task

Inputs are finite floating [batch,2,time,vocab] logits and int64 [batch,2,time] aligned response targets; pair index 0 is chosen, 1 rejected, and -100 masks non-response positions. Sum valid token log probabilities for each response, not their length average. Return mean(softplus(-beta*((policy_chosen-policy_rejected)-(reference_chosen-reference_rejected)))). Detach all reference logits. Every response needs a valid target. Reject bad labels, shape, empty batches and nonpositive/nonfinite beta. This is the DPO objective, not a claim of aligned behavior from passing a small fixture.

Starter

import math
import torch
from torch.nn import functional as F

def dpo_loss(policy, reference, targets, beta=.1):
    # TODO: implement dpo_loss under the declared contract.
    return None
Inspect the worked answer
import math
import torch
from torch.nn import functional as F

def dpo_loss(policy, reference, targets, beta=.1):
    if policy.ndim!=4 or policy.shape[1]!=2 or min(policy.shape)==0 or policy.shape[-1]<2 or reference.shape!=policy.shape or targets.shape!=policy.shape[:-1]:raise ValueError('Expected [batch, pair=2, time, vocabulary] aligned logits and targets.')
    if not policy.is_floating_point() or not reference.is_floating_point() or targets.dtype!=torch.long or not torch.isfinite(policy).all() or not torch.isfinite(reference).all() or not math.isfinite(beta) or beta<=0:raise ValueError('Expected finite floating logits, int64 labels and beta > 0.')
    mask=targets!=-100
    if (mask.sum(-1)==0).any() or ((targets[mask]<0)|(targets[mask]>=policy.shape[-1])).any():raise ValueError('Every response needs valid in-vocabulary targets.')
    safe=targets.masked_fill(~mask,0)
    policy_sum=(policy.log_softmax(-1).gather(-1,safe.unsqueeze(-1)).squeeze(-1)*mask).sum(-1)
    reference_sum=(reference.detach().log_softmax(-1).gather(-1,safe.unsqueeze(-1)).squeeze(-1)*mask).sum(-1)
    margin=(policy_sum[:,0]-policy_sum[:,1])-(reference_sum[:,0]-reference_sum[:,1])
    result=F.softplus(-beta*margin).mean()
    return result

About this algorithm

How Differentiate response-masked Direct Preference Optimization works

The idea

Direct Preference Optimization fine-tunes a language model from pairs of responses to the same prompt, one chosen and one rejected, without training a reward model first. For each response it adds up the log probabilities of the response tokens, once under the policy being trained and once under a frozen reference model.

The quantity that matters is the margin: how much more the policy prefers the chosen response over the rejected one than the reference does. The loss is softplus(-beta * margin), which shrinks as the margin grows. Because the reference's own preference is subtracted, the policy earns nothing for preferences the reference already had, and that keeps it anchored to its starting behaviour. When policy and reference agree, the margin is zero and the loss is ln 2.

How it works

  1. Validate [batch, 2, time, vocab] logits, matching int64 targets, finite values and beta > 0; every response needs at least one unmasked target.
  2. Build mask = targets != -100 and replace masked targets with 0 in safe, so gather receives a legal index.
  3. Take log_softmax of the policy logits, gather the target log probabilities, multiply by mask and sum over time.
  4. Do the same with reference.detach(), so no gradient reaches the reference.
  5. Compute margin as the policy's chosen minus rejected sum, minus the reference's chosen minus rejected sum.
  6. Return F.softplus(-beta * margin).mean() over the batch.

What it costs

Loss work
O(batch·time·vocab)
Model passes
policy and reference
Gradients
policy only

The loss is one log-softmax over each logit tensor; in real training the expense is running two models on both responses, with only the policy keeping a graph.

Where it is used

  • Rafailov et al. introduced it in 'Direct Preference Optimization: Your Language Model is Secretly a Reward Model' (NeurIPS 2023).
  • Hugging Face's TRL library provides a DPOTrainer that takes prompt, chosen and rejected columns.
  • Meta's Llama 3 announcement lists DPO among the methods used to post-train the instruction-tuned models.

Watch out for

  • Averaging token log probabilities over the response length when the objective sums them, which changes the margin for responses of different lengths.
  • Letting gradients reach the reference: its logits must be detached, and the Lab checks that the reference tensor's grad stays None.
  • Passing -100 to gather as an index, which raises an error; substitute a valid index and cancel those positions with the mask.