Direct Preference Optimization
Derive DPO from KL-regularized RLHF and study its gradients, sequence likelihoods, training, evaluation and limitations.
After this lesson you can
- Derive DPO loss from the RLHF objective and Bradley-Terry, including cancellation of the partition function.
- Analyze the DPO gradient and explain the weight σ(r̂_l − r̂_w) that concentrates learning on misordered pairs.
- Implement DPO from scratch with masked response log-probs and precomputed reference log-probs.
- Train DPO with LoRA on a 0.5B to 1.5B model and monitor margins, implicit rewards and chosen and rejected log-probs.
- Diagnose likelihood displacement and length exploitation, and compare on-policy and off-policy data.
Before you start
Must we train a reward model?
You have an instruction and two responses: one was preferred to the other. In the previous lesson you learned to adjust a policy using a reward signal, a reference and a PPO loop. That route can explore new responses, but requires coordinating generation, evaluation, values and updates. Direct Preference Optimization, or DPO, proposes training directly on pairs using a fixed reference and a classification loss.
“Directly” describes the training procedure, not the disappearance of preferences, their assumptions or possible biases. The dataset may contain human annotations or labels from another model; know which each pair represents. The policy receives evidence only about observed comparisons, not an evaluation of all its possible responses.
From Gibbs to a pairwise loss
Fix a prompt , a reference positive on the finite response space, and a reward . For , the optimum of the KL-regularized RLHF objective satisfies
Solving for reveals an implicit reward from the optimal policy:
The last term depends on the prompt, but not the response. Under Bradley-Terry, the probability of preferring to is . On subtraction, cancels. Cancellation requires both responses to belong to the same prompt and use the same normalization. If comparing responses from different prompts, the constants cannot be eliminated this way.
Replace the unknown optimal policy with a parameterized policy and define the implicit reward margin
The DPO loss is binary log-loss . It is minimized on preference examples without running PPO or training another reward model during that optimization. Numerically, is preferable to evaluating the logarithm of a sigmoid that may round to zero.
The derivation does not say every finite DPO training run equals the RLHF optimum. The correspondence assumes the preference model, a reference with suitable support, normalization and a policy class capable of representing the solution; finite data, selection bias and imperfect optimization can make it fail. Pairwise preferences also identify only reward differences for each prompt. Rafailov and colleagues formalize this reward-class equivalence, not a general quality guarantee for arbitrary data.
What the gradient actually pushes
With the reference fixed, the gradient of one pair is
The gradient weight approaches one when the margin is badly ordered and zero when the positive margin is large. This is a weight for one pair, not a promise that each of its two probabilities moves in a particular direction when parameters are shared with other responses or examples. The descent update adds the difference of gradients, while the rest of the distribution must normalize too.
The of this parameterization scales the margin and its gradient and comes from regularization of the ideal objective. It is not an operational KL bound for finite-data DPO training. Changing it also changes loss and gradient scale; compare configurations with the same reference, record KL and use a reasonable tuning budget before attributing differences to a single factor.
A pair is a sequence, not a token average
For a response , probability is computed autoregressively:
Include EOS when it is part of the modeled response; exclude prompt and padding using a mask. In a causal model the logit predicting a token is at the previous position: align logits and labels before summing. Packed examples must also prevent attention between independent sequences. Truncation that removes part of the response changes the event probability and can even remove EOS; record the rule and use it identically for policy and reference.
Dividing by the number of tokens produces another objective, not the DPO formula above. Length matters because sums contain different numbers of terms. A correlation between length and preference can teach a shortcut; comparing similarly sized pairs, stratifying results and measuring quality with external criteria helps diagnose it, but does not alone show what caused a preference.
Precomputing reference log-probs saves passes during training only if reference, tokenizer, template, truncation, EOS and data remain unchanged. Store revisions and fingerprints for weights, tokens and mask. A cache with a different template can yield a plausible numerical loss while optimizing the wrong problem. Compare a sample of precomputed log-probs with fresh evaluation before use.
This example uses exact Bradley-Terry probabilities for both orders, not human preferences. With all pairs present and a positive reference, the population minimum recovers the Gibbs optimum for two prompts. The second trajectory uses an explicit shared parameterization to demonstrate displacement, without claiming it always occurs.
"""DPO tabular con etiquetas Bradley-Terry probabilísticas y dos prompts."""
import math
import numpy as np
np.set_printoptions(precision=8, suppress=True)
beta = 0.7
reference = np.array([[.5, .3, .2], [.2, .5, .3]])
rewards = np.array([[1., .4, -.2], [-.2, .3, .8]])
pairs = [(0, 1), (0, 2), (1, 2)]
def softmax(logits):
exp = np.exp(logits - np.max(logits, axis=-1, keepdims=True))
return exp / exp.sum(axis=-1, keepdims=True)
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def loss_grad(logits):
# Cada par aparece en ambos órdenes, ponderados por su probabilidad verdadera.
implicit = beta * (np.log(softmax(logits)) - np.log(reference))
result = 0.
grad = np.zeros_like(logits)
for x in range(len(logits)):
for i, j in pairs:
true_p = sigmoid(rewards[x, i] - rewards[x, j])
margin = implicit[x, i] - implicit[x, j]
result += true_p * np.logaddexp(0, -margin) + (1 - true_p) * np.logaddexp(0, margin)
derivative = beta * (sigmoid(margin) - true_p)
grad[x, i] += derivative
grad[x, j] -= derivative
count = len(logits) * len(pairs)
return result / count, grad / count
def displacement(beta, count=60, rate=.2):
theta = 1.
result = []
for step in range(count + 1):
p = softmax(np.array([0., theta, 2 * theta]))
margin = beta * (theta - 1.)
result.append((step, theta, np.log(p[1]), np.log(p[0]), p[2], margin))
theta += rate * beta * sigmoid(-margin)
return np.array(result)
optimal = softmax(np.log(reference) + rewards / beta)
logits = np.log(reference).copy()
loss0, analytical = loss_grad(logits)
eps = 1e-5
numerical = np.zeros_like(logits)
for x in range(logits.shape[0]):
for i in range(logits.shape[1]):
offset = np.zeros_like(logits); offset[x, i] = eps
numerical[x, i] = (loss_grad(logits + offset)[0] - loss_grad(logits - offset)[0]) / (2 * eps)
gradient_error = np.max(np.abs(analytical - numerical))
assert gradient_error < 1e-9
for _ in range(5000):
loss, grad = loss_grad(logits)
logits -= .5 * grad
fitted = softmax(logits)
max_error = np.max(np.abs(fitted - optimal))
assert max_error < 1e-5
for x in range(len(logits)):
implicit = beta * (np.log(optimal[x]) - np.log(reference[x]))
for i, j in pairs:
assert abs((implicit[i] - implicit[j]) - (rewards[x, i] - rewards[x, j])) < 1e-12
trace = displacement(beta)
assert np.all(np.diff(trace[:, 2]) < 0) and np.all(np.diff(trace[:, 3]) < 0)
assert np.all(np.diff(trace[:, 5]) > 0) and np.all(np.diff(trace[:, 4]) > 0)
exercise_margin = .1 * (2 - (-1))
print('Pérdida inicial:', loss0)
print('Gradiente: error máximo frente a diferencias finitas:', gradient_error)
print('Óptimo Gibbs por prompt:', optimal)
print('Política ajustada:', fitted)
print('Error máximo respecto al óptimo:', max_error)
print('Desplazamiento (paso, θ, log elegida, log rechazada, p otra, margen):')
print(' inicio:', trace[0]); print(' final:', trace[-1])
print('Ejercicio: margen, pérdida y peso:', exercise_margin, np.logaddexp(0, -exercise_margin), sigmoid(-exercise_margin))
print('Los pares ponderados representan expectativas Bradley-Terry exactas, no observaciones humanas.')When the margin improves and both probabilities fall
Likelihood displacement occurs when a preferred response’s probability decreases while the distribution changes. In DPO the margin can increase because the rejected response probability falls even faster. Mass must go to other responses, which can be better or worse: the margin’s sign alone does not decide.
Consider three responses with logits for rejected, chosen and other. The difference between the first two logits is exactly : increasing it also increases that difference, but the third response gains mass. The tabular lab computes probabilities and derivatives of this explicit model. It does not represent a measured LLM run; it demonstrates that the signs can coexist with shared parameters.
Razin and colleagues study benign and harmful displacement cases. In their experiment training refusal of SORRY-Bench prompts, Llama-3-8B-Instruct’s refusal rate on the training set moved from 74.4% to 33.4%. That number belongs to their protocol and evaluator; it is not a general DPO failure rate. Inspect chosen and rejected log-probs, held-out generations, length and external metrics, not only implicit-reward accuracy.
Train and measure
The dashboard includes two real QUICK-mode reports, both with the same two-pair validation holdout. The on-policy branch starts from the off-policy branch checkpoint; its displayed updates are additional and the axis does not equalize total budget. These samples and one seed verify the flow, not which method is better. SHA-256 fingerprints are 291aa2f406509c8999bb7d684c1f00bb58017b451cec89db943072f8d7fafaf9 for off-policy and cb4c404254ae9229ed9d1abfd0485a8c9fa092dc28f519b296e684cec94c6e02 for on-policy.
DPO from scratch with held-out evaluation
This cell uses Qwen2.5-0.5B-Instruct with LoRA and binarized UltraFeedback pairs. By default it downloads the pinned revision; with ORYON_REWARD_JSONL it reads local JSONL and records its fingerprint without assuming verified provenance. It requires the m20-l18 reward model in ORYON_REWARD_DIR and writes to ORYON_DPO_DIR. Set ORYON_DPO_BETA to a finite positive value to compare β; default is 0.1. Install PyTorch, Transformers, PEFT, datasets, huggingface-hub and safetensors. To verify the flow use ORYON_QUICK=1; ORYON_OFFLINE=1 requires cached weights and local JSONL.
Log probabilities are summed over response tokens and EOS, without scoring the prompt or subsequent template line break. The reference is precomputed with the adapter disabled and identified by fingerprints. Intermediate curves use validation; the reward-model test is held out and compared before and after the fixed fine-tuning run. Policy samples before and after are also evaluated with the same seed, but their external reward model is a learned signal, not truth or human judgment. A short test does not demonstrate a general improvement.
Report and checkpoints remain in the chosen folder. Output dpo-report.json contains metrics, responses and fingerprints; inspect texts before sharing them. To connect a verified report to this lesson’s dashboard, save a reviewed copy as src/widgets/m20/l20/dpo-results.json in the repository.
"""DPO por pares, referencia precalculada y evaluación con el RM de m20-l18."""
import gc
import hashlib
import json
import math
import os
import random
from collections.abc import Mapping
from pathlib import Path
import numpy as np
import torch
from datasets import load_dataset
from huggingface_hub import snapshot_download
from peft import LoraConfig, PeftModel, get_peft_model
from safetensors.torch import load_file
from torch.nn import functional as F
from transformers import AutoModel, AutoModelForCausalLM, AutoTokenizer
QUICK=os.getenv('ORYON_QUICK')=='1'
OFFLINE=os.getenv('ORYON_OFFLINE')=='1'
LOCAL=os.getenv('ORYON_REWARD_JSONL','')
REWARD=Path(os.getenv('ORYON_REWARD_DIR','./oryon-reward'))
OUT=Path(os.getenv('ORYON_DPO_DIR','./oryon-dpo'))
MODEL='Qwen/Qwen2.5-0.5B-Instruct'
REV='7ae557604adf67be50417f59c2c2f167def9a775'
DATA='HuggingFaceH4/ultrafeedback_binarized'
DATA_REV='3949bf5f8c17c394422ccfab0c31ea9c20bdeb85'
SEED=2020; BETA=float(os.getenv('ORYON_DPO_BETA','0.1')); MAX_CONTEXT=384
if not math.isfinite(BETA) or BETA<=0: raise ValueError('ORYON_DPO_BETA debe ser finito y positivo')
N_TRAIN,N_VAL,N_TEST=(8,2,2) if QUICK else (512,64,64)
UPDATES=2 if QUICK else 512
EVAL_EVERY=1 if QUICK else 64
NEW_TOKENS=24 if QUICK else 128
torch.set_num_threads(1)
def sha(text): return hashlib.sha256(text.encode('utf-8')).hexdigest()
def normal(text): return ' '.join(text.split()).casefold()
def file_hash(path):
h=hashlib.sha256()
with Path(path).open('rb') as f:
for b in iter(lambda:f.read(1048576),b''): h.update(b)
return h.hexdigest()
def write_json(path,value): path.write_text(json.dumps(value,ensure_ascii=False,indent=2),encoding='utf-8')
def hash_files(path): return {p.name:file_hash(p) for p in sorted(Path(path).glob('*.safetensors'))}
def unpack_ids(value): return value['input_ids'] if isinstance(value,Mapping) else value
def encode_pair(tok,row):
# No se admite que texto ordinario se interprete como control de plantilla.
for text in (row['prompt'],row['chosen'],row['rejected']):
if not isinstance(text,str) or not text.strip(): raise ValueError('Campo vacío')
if any(s and s in text for s in tok.all_special_tokens): raise ValueError('Grafía de control en contenido')
messages=[{'role':'user','content':row['prompt']}]
prefix=unpack_ids(tok.apply_chat_template(messages,tokenize=True,add_generation_prompt=True))
eos=tok.convert_tokens_to_ids('<|im_end|>')
if eos in (None,tok.unk_token_id): raise ValueError('Falta delimitador final')
output=[]
for answer in (row['chosen'],row['rejected']):
full=unpack_ids(tok.apply_chat_template(messages+[{'role':'assistant','content':answer}],
tokenize=True,add_generation_prompt=False))
if full[:len(prefix)]!=prefix: raise ValueError('La frontera de la plantilla no es composicional')
try: end=full.index(eos,len(prefix))
except ValueError as exc: raise ValueError('La respuesta carece de EOS') from exc
tail=full[end+1:]
if tail!=tok.encode('\n',add_special_tokens=False): raise ValueError('Sufijo de plantilla inesperado')
ids=full[:end+1]
if len(ids)>MAX_CONTEXT or end==len(prefix): raise ValueError('Respuesta vacía o fuera de contexto')
output.append({'ids':ids,'start':len(prefix),'response_tokens':len(ids)-len(prefix)})
return output[0],output[1]
def sequence_logp(model,ids,start):
if not 1<=start<len(ids): raise ValueError('Frontera de respuesta inválida')
x=torch.tensor([ids],dtype=torch.long,device='cuda')
logits=model(input_ids=x,attention_mask=torch.ones_like(x),use_cache=False).logits[0,start-1:-1].float()
target=x[0,start:]
return logits.log_softmax(-1).gather(1,target[:,None]).sum()
def dpo_loss(policy_chosen,policy_rejected,ref_chosen,ref_rejected,beta):
return F.softplus(-beta*((policy_chosen-ref_chosen)-(policy_rejected-ref_rejected)))
def raw_pairs():
if LOCAL:
with open(LOCAL,encoding='utf-8') as f:
for line in f:
row=json.loads(line)
if row.get('split')=='train_prefs': yield row
else:
if OFFLINE: raise ValueError('Modo sin red: fija ORYON_REWARD_JSONL')
yield from load_dataset(DATA,split='train_prefs',revision=DATA_REV,streaming=True)
def parse(row):
a,b=row.get('chosen'),row.get('rejected')
if not isinstance(a,list) or not isinstance(b,list) or len(a)!=2 or len(b)!=2: raise ValueError('Par inválido')
if not all(isinstance(m,dict) for m in a+b): raise ValueError('Mensaje inválido')
if [m.get('role') for m in a]!=['user','assistant'] or [m.get('role') for m in b]!=['user','assistant']:
raise ValueError('Roles inválidos')
q,c,r=a[0].get('content'),a[1].get('content'),b[1].get('content')
if not all(isinstance(t,str) and t.strip() for t in (q,c,r)) or q!=b[0].get('content') or c==r:
raise ValueError('Texto o prompt inválido')
sw,sl=row.get('score_chosen'),row.get('score_rejected')
if not isinstance(sw,(int,float)) or not isinstance(sl,(int,float)) or not math.isfinite(sw) or not math.isfinite(sl) or sw<=sl:
raise ValueError('Puntuaciones ausentes, empatadas o inconsistentes')
return {'prompt':q,'chosen':c,'rejected':r,'prompt_hash':sha(normal(q))}
def collect_pairs(tok,reward_report):
# Test solo de prompts no vistos en entrenamiento ni validación del RM previo.
denied=set(reward_report['train_prompt_hashes'])|set(reward_report['validation_prompt_hashes'])
allowed=set(reward_report['test_prompt_hashes']); test=[]; seen=set()
for item in reward_report['test']:
row={k:item[k] for k in ('prompt','chosen','rejected','prompt_hash')}
key=sha(normal(row['prompt']))
if key!=row['prompt_hash'] or key not in allowed or key in denied: raise ValueError('Test RM incoherente')
if key in seen: continue
try: c,r=encode_pair(tok,row)
except ValueError: continue
row.update({'chosen_enc':c,'rejected_enc':r}); test.append(row); seen.add(key)
if len(test)==N_TEST: break
if len(test)<N_TEST: raise ValueError('Faltan prompts test separados del RM')
# Excluir todos los prompts test RM, no solo los seleccionados para DPO.
blocked=allowed; train=[]; val=[]; seen=set()
for raw in raw_pairs():
try: row=parse(raw); c,r=encode_pair(tok,row)
except (ValueError,AttributeError,KeyError): continue
key=row['prompt_hash']
if key in blocked or key in seen: continue
seen.add(key); row.update({'chosen_enc':c,'rejected_enc':r})
bucket=val if int(key[:8],16)%10==0 else train
cap=N_VAL if bucket is val else N_TRAIN
if len(bucket)<cap: bucket.append(row)
if len(train)==N_TRAIN and len(val)==N_VAL: break
if len(train)!=N_TRAIN or len(val)!=N_VAL: raise ValueError('Faltan pares train o validación')
return train,val,test
def reference_scores(model,rows):
with torch.no_grad(),model.disable_adapter():
for row in rows:
c,r=row['chosen_enc'],row['rejected_enc']
row['ref_chosen']=float(sequence_logp(model,c['ids'],c['start']))
row['ref_rejected']=float(sequence_logp(model,r['ids'],r['start']))
if not math.isfinite(row['ref_chosen']+row['ref_rejected']): raise ValueError('Referencia no finita')
def reference_probe(model,row):
# Distribución completa de un estado fijo, no solo el token elegido.
c=row['chosen_enc']; x=torch.tensor([c['ids']],dtype=torch.long,device='cuda')
with torch.no_grad(),model.disable_adapter():
return model(input_ids=x,attention_mask=torch.ones_like(x),use_cache=False).logits[0,c['start']-1].float().cpu()
def evaluate(model,rows):
measures=[]
with torch.no_grad():
for row in rows:
c,r=row['chosen_enc'],row['rejected_enc']
pc=float(sequence_logp(model,c['ids'],c['start'])); pr=float(sequence_logp(model,r['ids'],r['start']))
implicit_c=BETA*(pc-row['ref_chosen']); implicit_r=BETA*(pr-row['ref_rejected'])
margin=implicit_c-implicit_r
measures.append({'prompt_hash':row['prompt_hash'],'chosen_logp':pc,'rejected_logp':pr,'margin':margin,
'chosen_implicit_reward':implicit_c,'rejected_implicit_reward':implicit_r,
'chosen_length':c['response_tokens'],'rejected_length':r['response_tokens'],
'loss':float(np.logaddexp(0.,-margin))})
acc=sum(1 if x['margin']>0 else .5 if x['margin']==0 else 0 for x in measures)/len(measures)
return {'pairs':len(measures),'accuracy_with_ties_half':acc,
'mean_chosen_logp':sum(x['chosen_logp'] for x in measures)/len(measures),
'mean_rejected_logp':sum(x['rejected_logp'] for x in measures)/len(measures),
'mean_chosen_implicit_reward':sum(x['chosen_implicit_reward'] for x in measures)/len(measures),
'mean_rejected_implicit_reward':sum(x['rejected_implicit_reward'] for x in measures)/len(measures),
'mean_margin':sum(x['margin'] for x in measures)/len(measures),
'mean_chosen_length':sum(x['chosen_length'] for x in measures)/len(measures),
'mean_rejected_length':sum(x['rejected_length'] for x in measures)/len(measures),
'mean_loss':sum(x['loss'] for x in measures)/len(measures),'rows':measures}
def generate(model,tok,rows):
result=[]
end_ids={tok.convert_tokens_to_ids('<|im_end|>'),tok.convert_tokens_to_ids('<|endoftext|>')}
if None in end_ids or len(end_ids)!=2: raise ValueError('Faltan los tokens de terminación')
with torch.inference_mode():
for row in rows:
prefix=unpack_ids(tok.apply_chat_template([{'role':'user','content':row['prompt']}],tokenize=True,add_generation_prompt=True))
if len(prefix)+NEW_TOKENS>MAX_CONTEXT: raise ValueError('Prompt de evaluación excede el horizonte')
prompt_seed=(SEED+1+int(row['prompt_hash'][:16],16))%(2**63-1)
generator=torch.Generator(device='cuda').manual_seed(prompt_seed)
actions=[]
for _ in range(NEW_TOKENS):
x=torch.tensor([prefix+actions],device='cuda')
logits=model(input_ids=x,use_cache=False).logits[0,-1].float()
action=int(torch.multinomial(logits.softmax(-1),1,generator=generator)); actions.append(action)
if action in end_ids: break
result.append({'prompt_hash':row['prompt_hash'],'prompt':row['prompt'],'seed':prompt_seed,'ids':actions,
'text':tok.decode(actions,skip_special_tokens=True,clean_up_tokenization_spaces=False),
'ended_with':tok.convert_ids_to_tokens(actions[-1]) if actions[-1] in end_ids else 'límite'})
return result
def score_external(test,generated):
meta=json.loads((REWARD/'reward-meta.json').read_text(encoding='utf-8'))
if file_hash(REWARD/meta['head_file'])!=meta['head_sha256'] or file_hash(REWARD/meta['adapter']/'adapter_model.safetensors')!=meta['adapter_sha256']:
raise ValueError('Las huellas del reward model no coinciden')
snap=Path(snapshot_download(meta['model'],revision=meta['revision'],local_files_only=OFFLINE,allow_patterns=['*.safetensors']))
if hash_files(snap)!=meta['weights_sha256']: raise ValueError('Pesos base del reward model no coinciden')
tok=AutoTokenizer.from_pretrained(REWARD/meta['adapter'],local_files_only=True)
base=AutoModel.from_pretrained(meta['model'],revision=meta['revision'],dtype=torch.float32,local_files_only=OFFLINE).to('cuda')
model=PeftModel.from_pretrained(base,REWARD/meta['adapter']).eval()
weight=load_file(str(REWARD/meta['head_file']),device='cpu')['weight'].to('cuda').float()
def score(q,a):
if any(s and s in q+a for s in tok.all_special_tokens): raise ValueError('Grafía de control en contenido')
ids=unpack_ids(tok.apply_chat_template([{'role':'user','content':q},{'role':'assistant','content':a}],tokenize=True,add_generation_prompt=False))
if len(ids)>meta['max_context']: raise ValueError('Respuesta completa excede contexto del RM')
x=torch.tensor([ids],device='cuda'); h=model(input_ids=x,attention_mask=torch.ones_like(x),use_cache=False).last_hidden_state[0,-1].float()
v=float((weight@h).item())
if not math.isfinite(v): raise ValueError('Recompensa no finita')
return v
with torch.inference_mode():
pairs=[]
for r in test:
try:
pairs.append({'prompt_hash':r['prompt_hash'],'chosen':score(r['prompt'],r['chosen']),
'rejected':score(r['prompt'],r['rejected'])})
except ValueError as exc:
pairs.append({'prompt_hash':r['prompt_hash'],'chosen':None,'rejected':None,'unavailable':str(exc)})
for samples in generated.values():
for r in samples:
try: r['reward']=score(r['prompt'],r['text'])
except ValueError as exc: r['reward']=None; r['reward_unavailable']=str(exc)
del weight,model,base,tok; gc.collect(); torch.cuda.empty_cache()
return pairs,generated
def main():
if not torch.cuda.is_available(): raise RuntimeError('Este laboratorio requiere CUDA')
OUT.mkdir(parents=True,exist_ok=True)
random.seed(SEED); np.random.seed(SEED); torch.manual_seed(SEED); torch.cuda.manual_seed_all(SEED)
reward_path=REWARD/'reward-report.json'
prior=json.loads(reward_path.read_text(encoding='utf-8'))
tok=AutoTokenizer.from_pretrained(MODEL,revision=REV,local_files_only=OFFLINE)
train,val,test=collect_pairs(tok,prior)
snap=Path(snapshot_download(MODEL,revision=REV,local_files_only=OFFLINE,
allow_patterns=['*.safetensors','tokenizer.json','tokenizer_config.json']))
hashes=hash_files(snap)
if not hashes: raise ValueError('No hay pesos base safetensors')
tokenizer_hashes={name:file_hash(snap/name) for name in ('tokenizer.json','tokenizer_config.json')}
base=AutoModelForCausalLM.from_pretrained(MODEL,revision=REV,dtype=torch.float32,local_files_only=OFFLINE).to('cuda')
base.config.use_cache=False
model=get_peft_model(base,LoraConfig(r=8,lora_alpha=16,lora_dropout=0.,bias='none',task_type='CAUSAL_LM',
target_modules=['q_proj','k_proj','v_proj','o_proj'])).eval()
named_trainable=[(name,p) for name,p in model.named_parameters() if p.requires_grad]
if not named_trainable or any('lora_' not in name for name,_ in named_trainable):
raise ValueError('Solo los adaptadores LoRA pueden entrenarse')
reference_scores(model,train+val+test)
probe_before=reference_probe(model,val[0])
reference_cache={name:[{'prompt_hash':r['prompt_hash'],'chosen_sha256':sha(r['chosen']),
'rejected_sha256':sha(r['rejected']),'chosen_logp':r['ref_chosen'],
'rejected_logp':r['ref_rejected'],
'chosen_start':r['chosen_enc']['start'],'rejected_start':r['rejected_enc']['start'],
'chosen_ids_sha256':sha(json.dumps(r['chosen_enc']['ids'],separators=(',',':'))),
'rejected_ids_sha256':sha(json.dumps(r['rejected_enc']['ids'],separators=(',',':')))} for r in rows]
for name,rows in (('train',train),('validation',val),('test',test))}
write_json(OUT/'reference-scores.json',reference_cache)
opt=torch.optim.AdamW([p for p in model.parameters() if p.requires_grad],lr=1e-5)
history=[]; generated={}; processed=0; supervised=0
def save(step):
path=OUT/f'checkpoint-{step}'; model.save_pretrained(path,safe_serialization=True)
tok.save_pretrained(path)
manifest={'step':step,'model':MODEL,'revision':REV,'base_weights_sha256':hashes,'beta':BETA,
'adapter_sha256':file_hash(path/'adapter_model.safetensors'),
'reference_scores_sha256':file_hash(OUT/'reference-scores.json')}
write_json(path/'manifest.json',manifest)
return manifest
checkpoints=[save(0)]
torch.manual_seed(SEED+1); torch.cuda.manual_seed_all(SEED+1)
generated['before']=generate(model,tok,test)
test_before=evaluate(model,test)
history.append({'step':0,'validation':evaluate(model,val),'processed_tokens':0,'supervised_tokens':0})
for step in range(1,UPDATES+1):
row=train[(step-1)%len(train)]; c,r=row['chosen_enc'],row['rejected_enc']
opt.zero_grad(set_to_none=True)
pc=sequence_logp(model,c['ids'],c['start']); pr=sequence_logp(model,r['ids'],r['start'])
loss=dpo_loss(pc,pr,row['ref_chosen'],row['ref_rejected'],BETA)
if not torch.isfinite(loss): raise ValueError('Pérdida DPO no finita')
loss.backward(); torch.nn.utils.clip_grad_norm_([p for p in model.parameters() if p.requires_grad],1.); opt.step()
processed+=len(c['ids'])+len(r['ids']); supervised+=c['response_tokens']+r['response_tokens']
if step%EVAL_EVERY==0 or step==UPDATES:
checkpoints.append(save(step))
history.append({'step':step,'training_loss':float(loss.detach()),'validation':evaluate(model,val),
'processed_tokens':processed,'supervised_tokens':supervised})
test_after=evaluate(model,test)
probe_after=reference_probe(model,val[0])
reference_change=float((probe_after-probe_before).abs().max())
if not torch.allclose(probe_before,probe_after,atol=2e-5,rtol=2e-5):
raise ValueError('La distribución de referencia ha cambiado')
del probe_before,probe_after
torch.manual_seed(SEED+1); torch.cuda.manual_seed_all(SEED+1)
generated['after']=generate(model,tok,test)
del pc,pr,loss
del opt,model,base,tok; gc.collect(); torch.cuda.empty_cache()
pairs,generated=score_external(test,generated)
scored_pairs=[r for r in pairs if r['chosen'] is not None and r['rejected'] is not None]
reward_metrics={'pair_accuracy_with_ties_half':sum(1 if r['chosen']>r['rejected'] else .5 if r['chosen']==r['rejected'] else 0 for r in scored_pairs)/len(scored_pairs) if scored_pairs else None,
'pair_scored':len(scored_pairs),'pair_requested':len(pairs),
'sample_reward_mean':{name:(sum(r['reward'] for r in rows if r['reward'] is not None)/sum(r['reward'] is not None for r in rows)) if any(r['reward'] is not None for r in rows) else None for name,rows in generated.items()},
'sample_scored':{name:sum(r['reward'] is not None for r in rows) for name,rows in generated.items()},
'sample_requested':{name:len(rows) for name,rows in generated.items()}}
before={r['prompt_hash']:r['reward'] for r in generated['before'] if r['reward'] is not None}
after={r['prompt_hash']:r['reward'] for r in generated['after'] if r['reward'] is not None}
paired=[after[key]-before[key] for key in before.keys() & after.keys()]
reward_metrics['paired_prompts']=len(paired)
reward_metrics['paired_reward_change']=sum(paired)/len(paired) if paired else None
data_meta=({'kind':'JSONL local, origen no verificado','sha256':file_hash(LOCAL)} if LOCAL else
{'kind':'Hugging Face','id':DATA,'revision':DATA_REV})
report={'model':MODEL,'revision':REV,'base_weights_sha256':hashes,'tokenizer_sha256':tokenizer_hashes,
'quick':QUICK,'seed':SEED,'beta':BETA,
'data_policy':'pares de corpus fuera de política',
'source':data_meta,'reward_report_sha256':file_hash(reward_path),
'split_prompt_hashes':{'train':[r['prompt_hash'] for r in train],'validation':[r['prompt_hash'] for r in val],
'test':[r['prompt_hash'] for r in test]},
'reference':{'description':'base congelada con adaptador desactivado, sumas precalculadas por respuesta con EOS',
'scores_sha256':file_hash(OUT/'reference-scores.json'),
'max_probe_logit_change':reference_change,
'processed_tokens':sum(len(r['chosen_enc']['ids'])+len(r['rejected_enc']['ids']) for r in train+val+test)},
'training':{'updates':UPDATES,'learning_rate':1e-5,'rank':8,'alpha':16,'dropout':0,
'max_context':MAX_CONTEXT,'batch_pairs':1},'checkpoints':checkpoints,'history':history,
'heldout_before':test_before,'heldout_after':test_after,
'generation':{'seed_rule':'(2021 + primeros 64 bits del hash del prompt) módulo (2^63-1)',
'temperature':1,'top_k':None,'top_p':None,'max_new_tokens':NEW_TOKENS,
'end_tokens':['<|im_end|>','<|endoftext|>']},
'external_reward':{'metadata_sha256':file_hash(REWARD/'reward-meta.json'),'metrics':reward_metrics,
'test_pairs':pairs,'generated':generated,
'limitation':'Modelo aprendido sobre preferencias; no es verdad ni evaluación humana.'},
'limitations':'Una semilla y evaluación pequeña. Sin equivalencia entre etiquetas sintéticas y humanas. Separación por prompt exacto; no detecta paráfrasis.'}
write_json(OUT/'dpo-report.json',report)
print('Train/val/test:',len(train),len(val),len(test),'actualizaciones:',UPDATES,flush=True)
print('Log-probabilidades y margen:',json.dumps(history[-1]['validation'],ensure_ascii=False),flush=True)
print('Informe:',OUT/'dpo-report.json',flush=True)
if __name__=='__main__': main()npm run lab and open the connection link.On-policy and off-policy preferences
An on-policy dataset is obtained by sampling responses from the policy being studied, while an off-policy dataset comes from another distribution. In an iterative procedure, record exactly which checkpoint generated each pair: after training, those data are no longer strictly from the current policy. No dataset covers all prompts or responses, and an automatic labeler brings its own biases.
For comparison, retain a prompt-held-out set and separate hyperparameter selection from final evaluation. Match or declare pair counts, training budget, labels, reference and generation rules. If the same reward model labels and evaluates, it is not an independent evaluator. Comparing with another model or human annotations answers a different question, though neither eliminates all error.
This cell generates preferences using a frozen copy of checkpoint-0 from the previous DPO and labels them with the m20-l18 reward model. It performs one round from that initial policy: it is not an iterative algorithm resampling after each update. Sampling uses full softmax at temperature 1 and a reproducible per-prompt seed. To retain exactly the preceding cell’s mask, only responses that naturally end in <|im_end|> and whose tokens survive decoding and re-encoding unchanged are accepted; attempts and rejections are recorded. This selection conditions the pairs and is not equivalent to taking every policy sample. A quick run may not obtain enough pairs and will stop without inventing data.
The same training prompts, validation holdout, prompt-separated test, initial checkpoint, base reference and summed response loss from the previous cell are reused. The reward model ranks each pair; ties and pairs too long for that model are counted and excluded without truncating responses. Both branches use the same number of updates and optimizer, but selection, labels, sequence length, generation tokens and judge calls may differ. The report records those budgets separately; a result difference does not itself identify the effect of data origin. Common validation contains off-policy pairs and does not automatically measure newly generated response quality.
Before training, loss and a gradient are compared against real TRL 1.17.1 DPOTrainer._compute_loss with the same mask and reference log-probs; the auxiliary adapter merely presents TRL with the same logits in its merged format. Install trl==1.17.1, torch, transformers, peft, datasets, huggingface_hub and safetensors. You need the previous DPO artifacts in ORYON_DPO_DIR and the saved reward model in ORYON_REWARD_DIR; ORYON_DPO_BETA must match the previous branch. ORYON_ONPOLICY_DIR changes the output folder. ORYON_QUICK=1 limits data and updates, while normal mode retains the full budget stated in the previous cell. For offline local data, retain ORYON_REWARD_JSONL and ORYON_OFFLINE=1 with the same snapshots. The comparison is checked when running this cell with CUDA and TRL installed.
"""DPO dentro de política: pares generados, juez y contraste real con TRL."""
import gc, hashlib, json, math, os, random
from collections import defaultdict
from collections.abc import Mapping
from pathlib import Path
from types import SimpleNamespace
import numpy as np
import torch
from datasets import load_dataset
from huggingface_hub import snapshot_download
from peft import PeftModel
from safetensors.torch import load_file
from torch.nn import functional as F
from transformers import AutoModel, AutoModelForCausalLM, AutoTokenizer
QUICK = os.getenv('ORYON_QUICK') == '1'
OFFLINE = os.getenv('ORYON_OFFLINE') == '1'
LOCAL = os.getenv('ORYON_REWARD_JSONL', '')
REWARD = Path(os.getenv('ORYON_REWARD_DIR', './oryon-reward'))
BASELINE = Path(os.getenv('ORYON_DPO_DIR', './oryon-dpo'))
OUT = Path(os.getenv('ORYON_ONPOLICY_DIR', './oryon-onpolicy'))
MODEL = 'Qwen/Qwen2.5-0.5B-Instruct'
REV = '7ae557604adf67be50417f59c2c2f167def9a775'
DATA = 'HuggingFaceH4/ultrafeedback_binarized'
DATA_REV = '3949bf5f8c17c394422ccfab0c31ea9c20bdeb85'
SEED = 2020
BETA = float(os.getenv('ORYON_DPO_BETA', '.1'))
if not math.isfinite(BETA) or BETA <= 0: raise ValueError('ORYON_DPO_BETA debe ser finito y positivo')
MAX_CONTEXT = 384
N_TRAIN, N_VAL, N_TEST = (8, 2, 2) if QUICK else (512, 64, 64)
UPDATES = 2 if QUICK else 512
MAX_NEW = 24 if QUICK else 128
MAX_ATTEMPTS = 12 if QUICK else 24
torch.set_num_threads(1)
# Copiadas de la celda DPO anterior: misma plantilla, máscara y referencia.
def sha(text): return hashlib.sha256(text.encode('utf-8')).hexdigest()
def normal(text): return ' '.join(text.split()).casefold()
def file_hash(path):
h=hashlib.sha256()
with Path(path).open('rb') as f:
for b in iter(lambda:f.read(1048576),b''): h.update(b)
return h.hexdigest()
def unpack_ids(value): return value['input_ids'] if isinstance(value,Mapping) else value
def encode_pair(tok,row):
# No se admite que texto ordinario se interprete como control de plantilla.
for text in (row['prompt'],row['chosen'],row['rejected']):
if not isinstance(text,str) or not text.strip(): raise ValueError('Campo vacío')
if any(s and s in text for s in tok.all_special_tokens): raise ValueError('Grafía de control en contenido')
messages=[{'role':'user','content':row['prompt']}]
prefix=unpack_ids(tok.apply_chat_template(messages,tokenize=True,add_generation_prompt=True))
eos=tok.convert_tokens_to_ids('<|im_end|>')
if eos in (None,tok.unk_token_id): raise ValueError('Falta delimitador final')
output=[]
for answer in (row['chosen'],row['rejected']):
full=unpack_ids(tok.apply_chat_template(messages+[{'role':'assistant','content':answer}],
tokenize=True,add_generation_prompt=False))
if full[:len(prefix)]!=prefix: raise ValueError('La frontera de la plantilla no es composicional')
try: end=full.index(eos,len(prefix))
except ValueError as exc: raise ValueError('La respuesta carece de EOS') from exc
tail=full[end+1:]
if tail!=tok.encode('\n',add_special_tokens=False): raise ValueError('Sufijo de plantilla inesperado')
ids=full[:end+1]
if len(ids)>MAX_CONTEXT or end==len(prefix): raise ValueError('Respuesta vacía o fuera de contexto')
output.append({'ids':ids,'start':len(prefix),'response_tokens':len(ids)-len(prefix)})
return output[0],output[1]
def sequence_logp(model,ids,start):
if not 1<=start<len(ids): raise ValueError('Frontera de respuesta inválida')
x=torch.tensor([ids],dtype=torch.long,device='cuda')
logits=model(input_ids=x,attention_mask=torch.ones_like(x),use_cache=False).logits[0,start-1:-1].float()
target=x[0,start:]
return logits.log_softmax(-1).gather(1,target[:,None]).sum()
def dpo_loss(policy_chosen,policy_rejected,ref_chosen,ref_rejected,beta):
return F.softplus(-beta*((policy_chosen-ref_chosen)-(policy_rejected-ref_rejected)))
def raw_pairs():
if LOCAL:
with open(LOCAL,encoding='utf-8') as f:
for line in f:
row=json.loads(line)
if row.get('split')=='train_prefs': yield row
else:
if OFFLINE: raise ValueError('Modo sin red: fija ORYON_REWARD_JSONL')
yield from load_dataset(DATA,split='train_prefs',revision=DATA_REV,streaming=True)
def parse(row):
a,b=row.get('chosen'),row.get('rejected')
if not isinstance(a,list) or not isinstance(b,list) or len(a)!=2 or len(b)!=2: raise ValueError('Par inválido')
if not all(isinstance(m,dict) for m in a+b): raise ValueError('Mensaje inválido')
if [m.get('role') for m in a]!=['user','assistant'] or [m.get('role') for m in b]!=['user','assistant']:
raise ValueError('Roles inválidos')
q,c,r=a[0].get('content'),a[1].get('content'),b[1].get('content')
if not all(isinstance(t,str) and t.strip() for t in (q,c,r)) or q!=b[0].get('content') or c==r:
raise ValueError('Texto o prompt inválido')
sw,sl=row.get('score_chosen'),row.get('score_rejected')
if not isinstance(sw,(int,float)) or not isinstance(sl,(int,float)) or not math.isfinite(sw) or not math.isfinite(sl) or sw<=sl:
raise ValueError('Puntuaciones ausentes, empatadas o inconsistentes')
return {'prompt':q,'chosen':c,'rejected':r,'prompt_hash':sha(normal(q))}
def collect_pairs(tok,reward_report):
# Test solo de prompts no vistos en entrenamiento ni validación del RM previo.
denied=set(reward_report['train_prompt_hashes'])|set(reward_report['validation_prompt_hashes'])
allowed=set(reward_report['test_prompt_hashes']); test=[]; seen=set()
for item in reward_report['test']:
row={k:item[k] for k in ('prompt','chosen','rejected','prompt_hash')}
key=sha(normal(row['prompt']))
if key!=row['prompt_hash'] or key not in allowed or key in denied: raise ValueError('Test RM incoherente')
if key in seen: continue
try: c,r=encode_pair(tok,row)
except ValueError: continue
row.update({'chosen_enc':c,'rejected_enc':r}); test.append(row); seen.add(key)
if len(test)==N_TEST: break
if len(test)<N_TEST: raise ValueError('Faltan prompts test separados del RM')
# Excluir todos los prompts test RM, no solo los seleccionados para DPO.
blocked=allowed; train=[]; val=[]; seen=set()
for raw in raw_pairs():
try: row=parse(raw); c,r=encode_pair(tok,row)
except (ValueError,AttributeError,KeyError): continue
key=row['prompt_hash']
if key in blocked or key in seen: continue
seen.add(key); row.update({'chosen_enc':c,'rejected_enc':r})
bucket=val if int(key[:8],16)%10==0 else train
cap=N_VAL if bucket is val else N_TRAIN
if len(bucket)<cap: bucket.append(row)
if len(train)==N_TRAIN and len(val)==N_VAL: break
if len(train)!=N_TRAIN or len(val)!=N_VAL: raise ValueError('Faltan pares train o validación')
return train,val,test
def reference_scores(model,rows):
with torch.no_grad(),model.disable_adapter():
for row in rows:
c,r=row['chosen_enc'],row['rejected_enc']
row['ref_chosen']=float(sequence_logp(model,c['ids'],c['start']))
row['ref_rejected']=float(sequence_logp(model,r['ids'],r['start']))
if not math.isfinite(row['ref_chosen']+row['ref_rejected']): raise ValueError('Referencia no finita')
def evaluate(model,rows):
measures=[]
with torch.no_grad():
for row in rows:
c,r=row['chosen_enc'],row['rejected_enc']
pc=float(sequence_logp(model,c['ids'],c['start'])); pr=float(sequence_logp(model,r['ids'],r['start']))
implicit_c=BETA*(pc-row['ref_chosen']); implicit_r=BETA*(pr-row['ref_rejected'])
margin=implicit_c-implicit_r
measures.append({'prompt_hash':row['prompt_hash'],'chosen_logp':pc,'rejected_logp':pr,'margin':margin,
'chosen_implicit_reward':implicit_c,'rejected_implicit_reward':implicit_r,
'chosen_length':c['response_tokens'],'rejected_length':r['response_tokens'],
'loss':float(np.logaddexp(0.,-margin))})
acc=sum(1 if x['margin']>0 else .5 if x['margin']==0 else 0 for x in measures)/len(measures)
return {'pairs':len(measures),'accuracy_with_ties_half':acc,
'mean_chosen_logp':sum(x['chosen_logp'] for x in measures)/len(measures),
'mean_rejected_logp':sum(x['rejected_logp'] for x in measures)/len(measures),
'mean_chosen_implicit_reward':sum(x['chosen_implicit_reward'] for x in measures)/len(measures),
'mean_rejected_implicit_reward':sum(x['rejected_implicit_reward'] for x in measures)/len(measures),
'mean_margin':sum(x['margin'] for x in measures)/len(measures),
'mean_chosen_length':sum(x['chosen_length'] for x in measures)/len(measures),
'mean_rejected_length':sum(x['rejected_length'] for x in measures)/len(measures),
'mean_loss':sum(x['loss'] for x in measures)/len(measures),'rows':measures}
def write_json(path, data):
path.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding='utf-8')
def hashes(path): return {p.name:file_hash(p) for p in sorted(Path(path).glob('*.safetensors'))}
def candidate(model, tok, prompt, generator):
prefix = unpack_ids(tok.apply_chat_template([{'role':'user','content':prompt}], tokenize=True,
add_generation_prompt=True))
if len(prefix)+MAX_NEW > MAX_CONTEXT: raise ValueError('El prompt no deja sitio al horizonte de generación')
eos = tok.convert_tokens_to_ids('<|im_end|>')
end_text = tok.convert_tokens_to_ids('<|endoftext|>')
tokens=[]
with torch.inference_mode():
for _ in range(MAX_NEW):
x = torch.tensor([prefix+tokens],device='cuda')
logits = model(input_ids=x,use_cache=False).logits[0,-1].float()
action = int(torch.multinomial(logits.softmax(-1),1,generator=generator).item())
tokens.append(action)
if action in (eos, end_text): break
# La máscara compartida incluye im_end; los truncados o endoftext no se reparan.
if tokens[-1] != eos or any(t in tok.all_special_ids for t in tokens[:-1]): return None,len(tokens)
answer = tok.decode(tokens[:-1],skip_special_tokens=False,clean_up_tokenization_spaces=False)
if not answer.strip(): return None,len(tokens)
row={'prompt':prompt,'chosen':answer,'rejected':answer,'prompt_hash':sha(normal(prompt))}
try: encoded,_ = encode_pair(tok,row)
except ValueError: return None,len(tokens)
if encoded['ids'][encoded['start']:] != tokens: return None,len(tokens)
return {'text':answer,'tokens':tokens},len(tokens)
def sample_pairs(model, tok, rows):
result=[]; rejected=0; attempts=0; generation_tokens=0; context_skips=0
model.eval()
for row in rows:
prompt_seed=(SEED+17+int(row['prompt_hash'][:16],16))%(2**63-1)
generator=torch.Generator(device='cuda').manual_seed(prompt_seed)
samples=[]
prefix=unpack_ids(tok.apply_chat_template([{'role':'user','content':row['prompt']}],tokenize=True,add_generation_prompt=True))
if len(prefix)+MAX_NEW>MAX_CONTEXT:
context_skips+=1; continue
for _ in range(MAX_ATTEMPTS):
item,token_count=candidate(model,tok,row['prompt'],generator)
attempts+=1; generation_tokens+=token_count
if item is None or any(item['tokens']==x['tokens'] for x in samples):
rejected+=1; continue
samples.append(item)
if len(samples)==2: break
if len(samples)==2:
result.append({'prompt':row['prompt'],'prompt_hash':row['prompt_hash'],
'generation_seed':prompt_seed,'samples':samples})
return result,{'rejected_candidates':rejected,'attempts':attempts,'generated_tokens':generation_tokens,
'prompt_context_skips':context_skips,
'seed_rule':'(2020+17+int(prompt_hash[:16],16)) % (2**63-1)'}
def label_pairs(rows):
meta=json.loads((REWARD/'reward-meta.json').read_text(encoding='utf-8'))
if file_hash(REWARD/meta['head_file']) != meta['head_sha256'] or file_hash(REWARD/meta['adapter']/'adapter_model.safetensors') != meta['adapter_sha256']:
raise ValueError('Las huellas del reward model no coinciden')
snapshot=Path(snapshot_download(meta['model'],revision=meta['revision'],local_files_only=OFFLINE,allow_patterns=['*.safetensors']))
if hashes(snapshot)!=meta['weights_sha256']: raise ValueError('Pesos base del juez no coinciden')
tok=AutoTokenizer.from_pretrained(REWARD/meta['adapter'],local_files_only=True)
base=AutoModel.from_pretrained(meta['model'],revision=meta['revision'],dtype=torch.float32,
local_files_only=OFFLINE).to('cuda')
model=PeftModel.from_pretrained(base,REWARD/meta['adapter']).eval()
weight=load_file(str(REWARD/meta['head_file']),device='cpu')['weight'].to('cuda').float()
judge_calls=0
def score(prompt,answer):
nonlocal judge_calls
if any(s and s in prompt+answer for s in tok.all_special_tokens): raise ValueError('Grafía de control en texto')
ids=unpack_ids(tok.apply_chat_template([{'role':'user','content':prompt},{'role':'assistant','content':answer}],
tokenize=True,add_generation_prompt=False))
if len(ids)>meta['max_context']: raise ValueError('Respuesta fuera del contexto del juez')
x=torch.tensor([ids],device='cuda')
judge_calls+=1
h=model(input_ids=x,attention_mask=torch.ones_like(x),use_cache=False,return_dict=True).last_hidden_state[0,-1].float()
value=float((weight@h).item())
if not math.isfinite(value): raise ValueError('Recompensa no finita')
return value
labelled=[]; ties=0; unavailable=defaultdict(int)
with torch.inference_mode():
for row in rows:
a,b=row['samples']
try: sa,sb=score(row['prompt'],a['text']),score(row['prompt'],b['text'])
except ValueError as exc:
unavailable[str(exc)]+=1; continue
if sa==sb: ties+=1; continue
chosen,rejected=(a,b) if sa>sb else (b,a)
labelled.append({'prompt':row['prompt'],'prompt_hash':row['prompt_hash'],
'chosen':chosen['text'],'rejected':rejected['text'],
'chosen_tokens':chosen['tokens'],'rejected_tokens':rejected['tokens'],
'judge_chosen':max(sa,sb),'judge_rejected':min(sa,sb)})
del model,base,weight,tok; gc.collect(); torch.cuda.empty_cache()
return labelled,{'ties':ties,'unscored_by_reason':dict(unavailable),'judge_forward_calls':judge_calls}, {'model':meta['model'],'revision':meta['revision'],
'adapter_sha256':meta['adapter_sha256'],'head_sha256':meta['head_sha256'],
'weights_sha256':meta['weights_sha256']}
def compare_trl(model, tok, row):
# Se invoca el método real de TRL 1.17.1; el adaptador expone su API de logits fusionados.
import trl
from trl import DPOTrainer
if trl.__version__ != '1.17.1': raise RuntimeError('Este contraste requiere TRL 1.17.1')
a,b=row['chosen_enc'],row['rejected_enc']
maxlen=max(len(a['ids']),len(b['ids']))
pad=tok.pad_token_id if tok.pad_token_id is not None else 0
data=[]; attention=[]; mask=[]
for v in (a,b):
n=len(v['ids']); data.append(v['ids']+[pad]*(maxlen-n))
attention.append([1]*n+[0]*(maxlen-n))
mask.append([0]*v['start']+[1]*(n-v['start'])+[0]*(maxlen-n))
inputs={'input_ids':torch.tensor(data,device='cuda'), 'attention_mask':torch.tensor(attention,device='cuda'),
'completion_mask':torch.tensor(mask,device='cuda'),
'ref_chosen_logps':torch.tensor([row['ref_chosen']],device='cuda'),
'ref_rejected_logps':torch.tensor([row['ref_rejected']],device='cuda')}
class ForwardAdapter:
training=False
def __call__(self,input_ids,attention_mask,labels,use_cache,fused_lm_head):
logits=model(input_ids=input_ids,attention_mask=attention_mask,use_cache=False).logits[:,:-1].float()
target=labels[:,1:]; valid=target.ne(-100); safe=target.masked_fill(~valid,0)
lp=logits.log_softmax(-1); picked=lp.gather(-1,safe.unsqueeze(-1)).squeeze(-1)*valid
entropy=-(lp.exp()*lp).sum(-1)
return SimpleNamespace(log_probs=picked,entropy=entropy,mean_logits=logits.mean(-1),is_top1=logits.argmax(-1).eq(safe))
wrapped=ForwardAdapter()
accelerator=SimpleNamespace(device=torch.device('cuda'),gather=lambda x:x,gather_for_metrics=lambda x:x)
state=SimpleNamespace(model=wrapped,accelerator=accelerator,aux_loss_enabled=False,ld_alpha=None,
precompute_ref_logps=True,f_divergence_type='reverse_kl',loss_types=['sigmoid'],
loss_weights=[1.],beta=BETA,use_weighting=False,
_metrics=defaultdict(lambda:defaultdict(list)),_total_train_tokens=0,_tp_size=1)
actual=DPOTrainer._compute_loss(state,wrapped,inputs,False)
pc=sequence_logp(model,a['ids'],a['start']); pr=sequence_logp(model,b['ids'],b['start'])
ours=dpo_loss(pc,pr,torch.tensor(row['ref_chosen'],device='cuda'),
torch.tensor(row['ref_rejected'],device='cuda'),BETA)
if not torch.allclose(actual,ours,atol=2e-4,rtol=2e-4): raise ValueError('La pérdida de TRL no coincide')
name,parameter=next((n,p) for n,p in model.named_parameters() if p.requires_grad and 'lora_B' in n)
gt,=torch.autograd.grad(actual,parameter); go,=torch.autograd.grad(ours,parameter)
if not torch.allclose(gt,go,atol=2e-5,rtol=5e-4): raise ValueError('El gradiente de TRL no coincide')
return {'trl_version':trl.__version__,'loss_ours':float(ours.detach()),'loss_trl':float(actual.detach()),
'gradient_parameter':name,'max_gradient_abs_difference':float((gt-go).abs().max())}
def main():
if not torch.cuda.is_available(): raise RuntimeError('El laboratorio requiere CUDA')
try:
import trl
except ImportError as exc: raise RuntimeError('Instala TRL 1.17.1 para el contraste real') from exc
if trl.__version__!='1.17.1': raise RuntimeError('Este contraste requiere TRL 1.17.1')
OUT.mkdir(parents=True,exist_ok=True)
random.seed(SEED); np.random.seed(SEED); torch.manual_seed(SEED); torch.cuda.manual_seed_all(SEED)
baseline=json.loads((BASELINE/'dpo-report.json').read_text(encoding='utf-8'))
if baseline['model']!=MODEL or baseline['revision']!=REV or baseline['quick']!=QUICK or baseline['beta']!=BETA:
raise ValueError('La rama off-policy no comparte modelo, modo y beta')
first=BASELINE/'checkpoint-0'
manifest=json.loads((first/'manifest.json').read_text(encoding='utf-8'))
if manifest['adapter_sha256']!=file_hash(first/'adapter_model.safetensors'):
raise ValueError('La huella del checkpoint inicial no coincide')
if manifest['reference_scores_sha256']!=file_hash(BASELINE/'reference-scores.json'):
raise ValueError('La huella de la referencia no coincide')
snap=Path(snapshot_download(MODEL,revision=REV,local_files_only=OFFLINE,
allow_patterns=['*.safetensors','tokenizer.json','tokenizer_config.json']))
if hashes(snap)!=baseline['base_weights_sha256']: raise ValueError('Pesos base distintos a la rama off-policy')
token_hashes={name:file_hash(snap/name) for name in ('tokenizer.json','tokenizer_config.json')}
if token_hashes!=baseline['tokenizer_sha256']: raise ValueError('Tokenizador distinto a la rama off-policy')
tok=AutoTokenizer.from_pretrained(MODEL,revision=REV,local_files_only=OFFLINE)
prior=json.loads((REWARD/'reward-report.json').read_text(encoding='utf-8'))
train,val,test=collect_pairs(tok,prior)
for name,rows in [('train',train),('validation',val),('test',test)]:
if [r['prompt_hash'] for r in rows] != baseline['split_prompt_hashes'][name]:
raise ValueError('La selección de prompts difiere de la rama off-policy')
base=AutoModelForCausalLM.from_pretrained(MODEL,revision=REV,dtype=torch.float32,
local_files_only=OFFLINE).to('cuda')
frozen=PeftModel.from_pretrained(base,first,is_trainable=False).eval()
sampled,sampling=sample_pairs(frozen,tok,train)
write_json(OUT/'sampled-pairs.json',{'rows':sampled,'sampling':sampling,
'requested_prompts':len(train),'sampled_prompts':len(sampled)})
del frozen,base; gc.collect(); torch.cuda.empty_cache()
labelled,label_stats,reward_meta=label_pairs(sampled)
write_json(OUT/'on-policy-pairs.json',{'pairs':labelled,'labeling':label_stats,'reward':reward_meta})
if not labelled: raise ValueError('No hay pares válidos terminados en EOS y con preferencias distintas')
for row in labelled:
c,r=encode_pair(tok,row)
if c['ids'][c['start']:]!=row['chosen_tokens'] or r['ids'][r['start']:]!=row['rejected_tokens']:
raise ValueError('La codificación difiere de la muestra real')
row['chosen_enc'],row['rejected_enc']=c,r
base=AutoModelForCausalLM.from_pretrained(MODEL,revision=REV,dtype=torch.float32,
local_files_only=OFFLINE).to('cuda')
model=PeftModel.from_pretrained(base,first,is_trainable=True).eval()
reference_scores(model,labelled+val+test)
cached=json.loads((BASELINE/'reference-scores.json').read_text(encoding='utf-8'))
for name,rows in [('validation',val),('test',test)]:
if len(rows)!=len(cached[name]): raise ValueError('Tamaño diferente de referencia')
for row,old in zip(rows,cached[name]):
if row['prompt_hash']!=old['prompt_hash'] or sha(row['chosen'])!=old['chosen_sha256'] or sha(row['rejected'])!=old['rejected_sha256']:
raise ValueError('Respuesta retenida diferente')
for label in ('chosen','rejected'):
digest=sha(json.dumps(row[label+'_enc']['ids'],separators=(',',':')))
if (digest!=old[label+'_ids_sha256'] or row[label+'_enc']['start']!=old[label+'_start']
or not math.isclose(row['ref_'+label],old[label+'_logp'],abs_tol=2e-4,rel_tol=2e-4)):
raise ValueError('Máscara, tokens o referencia diferentes')
check=compare_trl(model,tok,labelled[0])
optimizer=torch.optim.AdamW([p for p in model.parameters() if p.requires_grad],lr=1e-5)
history=[{'step':0,'validation':evaluate(model,val),'processed_tokens':0,'supervised_tokens':0}]
processed=0; supervised=0
for step in range(1,UPDATES+1):
row=labelled[(step-1)%len(labelled)]; c,r=row['chosen_enc'],row['rejected_enc']
optimizer.zero_grad(set_to_none=True)
pc=sequence_logp(model,c['ids'],c['start']); pr=sequence_logp(model,r['ids'],r['start'])
loss=dpo_loss(pc,pr,row['ref_chosen'],row['ref_rejected'],BETA)
if not torch.isfinite(loss): raise ValueError('Pérdida DPO no finita')
loss.backward(); torch.nn.utils.clip_grad_norm_([p for p in model.parameters() if p.requires_grad],1.); optimizer.step()
processed+=len(c['ids'])+len(r['ids']); supervised+=c['response_tokens']+r['response_tokens']
if step%(1 if QUICK else 64)==0 or step==UPDATES:
model.save_pretrained(OUT/f'checkpoint-{step}',safe_serialization=True)
history.append({'step':step,'training_loss':float(loss.detach()),'validation':evaluate(model,val),
'processed_tokens':processed,'supervised_tokens':supervised})
result={'model':MODEL,'revision':REV,'beta':BETA,'quick':QUICK,'data_policy':'on-policy',
'initial_adapter_sha256':manifest['adapter_sha256'],'reference':'base con adaptador desactivado',
'source_off_policy_report_sha256':file_hash(BASELINE/'dpo-report.json'),
'judge':reward_meta,'attempts_per_prompt':MAX_ATTEMPTS,'sampled_prompts':len(sampled),
'sampling':sampling,'labeling':label_stats,'pairs':len(labelled),
'same_validation_prompt_hashes':[r['prompt_hash'] for r in val],
'history':history,'heldout':evaluate(model,test),'trl_check':check,
'off_policy_budget':{'processed_tokens':baseline['history'][-1]['processed_tokens'],
'supervised_tokens':baseline['history'][-1]['supervised_tokens'],
'updates':baseline['training']['updates']},
'limitations':'Diferentes respuestas y etiquetas, tokens y cómputo de generación/juez; las diferencias no aíslan el origen. La selección exige EOS natural e ida y vuelta exacta.'}
write_json(OUT/'on-policy-report.json',result)
print('Pares:',len(labelled),'TRL:',check,'presupuestos:',result['off_policy_budget'],history[-1],flush=True)
del optimizer,model,base; gc.collect(); torch.cuda.empty_cache()
if __name__=='__main__': main()npm run lab and open the connection link.Xu and colleagues found PPO advantages in their dialogue and code experiments. In Ivison and colleagues’ comparison of 13 billion parameter models, PPO surpassed DPO by a mean of 0.7 points on their metrics; they used datasets reduced to 60,908 examples except ChatArena, with 20,465 responses. These comparisons depend on models, budgets, feedback and evaluators. They do not establish that PPO always wins or that DPO is equivalent to online learning. Evaluate both methods on the task and distribution that matter to you.
Reading it as a token-level Q function
The derivation above treats a complete response as an action. In the prefix MDP, Rafailov and colleagues relate the optimal policy to a function of token actions. With deterministic concatenation transitions, terminal horizon, and zero terminal value convention, their equations for the regularized problem are
Combining the equations and summing over the trajectory cancels intermediate state values. The sum of rewards remains as . For two responses to the same prompt, also cancels in the difference. This is an interpretation under specific assumptions, not proof that any learned logit alone identifies a unique human reward or that training reached .
Exercises
import math
beta, logratio_w, logratio_l = .1, 2., -1.
margin = beta * (logratio_w - logratio_l)
loss = math.log1p(math.exp(-margin))
weight = 1 / (1 + math.exp(margin))
print('Margen:', margin, 'pérdida:', loss, 'peso:', weight)Step 1 of 3. Which term appears when solving for reward from the Gibbs optimum?
Step 1 of 3. What is the derivative of softplus(−m) with respect to m?
import numpy as np
def sequence_logprobs(logits, labels, mask):
pass
def dpo_loss(policy_w, policy_l, ref_w, ref_l, beta):
pass
DPO turns preferences for the same prompt into a logistic loss on log-ratios relative to a reference. Its apparent simplicity does not eliminate decisions about data, support, tokenization or independent evaluation.