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 NoneInspect 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