Beyond DPO: IPO, KTO, SimPO, ORPO and iterative optimization
Compare preference optimization objectives and design controlled evaluations, including iterative online DPO.
After this lesson you can
- Place RLHF, DPO and IPO in the ΨPO framework and explain why DPO overfits deterministic preferences.
- Implement IPO, KTO, SimPO and ORPO losses over the same log-probability function.
- Explain what removing the reference model gains and what it loses.
- Build an iterative DPO loop with policy-generated pairs labeled by a local judge.
- Design a fair comparison of objectives with per-method hyperparameter sweeps and multiple seeds.
Before you start
Many losses, different questions
In DPO a comparison teaches a difference in log-probabilities relative to a reference. But not all data arrive in pairs, not all labels are noisy, and not all teams can keep another reference in memory. IPO, KTO, SimPO and ORPO change different parts of that problem. Comparing names without comparing data, objectives and budgets can attribute to the algorithm what came from another decision.
The question running through this lesson is concrete: what happens to the response distribution as you continue optimizing a preference signal? First we study objectives you can calculate by hand; then we design experiments with held-out samples and a judge distinct from the signal being optimized.
ΨPO and deterministic preferences
The ΨPO framework of Azar and colleagues expresses preference objectives through a transformation of choice probabilities and regularization relative to the reference. Under the paper’s assumptions and Bradley-Terry model, the logit transformation connects the RLHF objective to DPO; the identity leads to IPO. This does not mean two practical implementations are equivalent for arbitrary datasets or parameterizations.
To see a difficulty, take two responses, a positive reference and a label that always prefers to . Define
The DPO loss for that pair is , with . It decreases as increases and has infimum zero when . In the binary case this leads to for any positive . With a softmax and finite parameters, however, both probabilities are positive: the infimum is not attained at a finite point. With more responses or pairs, incomplete coverage and shared parameters complicate the conclusion.
The KL of the regularized problem does not algebraically disappear. The subtlety is that the logit of a preference probability of exactly one diverges: in that idealization no finite coefficient offsets an infinite inferred reward difference. An unregularized Bradley-Terry reward model fitted to deterministic labels may also lack a finite optimum. If regularization is imposed or fitting is stopped early, you are comparing a different procedure, which must be explicitly described.
IPO: a finite margin
Identity Preference Optimization uses the identity transformation. With Azar and colleagues’ convention, one pair’s loss is written
Its minimum is at a finite log-ratio margin. In a space of exactly two responses with positive reference, . The IPO minimum assigns
That does not guarantee a neural model finds the minimum or identify responses never appearing in the data. Coverage, reference support and policy class matter. Nor should you numerically equate IPO’s and DPO’s without defining a comparison convention.
This cell’s functions and trajectories are explicit mathematical models. In the binary case the reference is uniform; the reward model is fitted to deterministic comparisons with an L2 penalty, so its finite difference depends on that choice. DPO and IPO curves are actual gradient-descent iterations, not language-model runs.
"""Pérdidas de preferencia y un experimento binario reproducible."""
import math
def sigmoid(x):
return 1 / (1 + math.exp(-x)) if x >= 0 else math.exp(x) / (1 + math.exp(x))
def softplus(x):
return max(x, 0) + math.log1p(math.exp(-abs(x)))
def objective(method, x, beta, tau, gamma, anchor=-2.):
if method == 'dpo': return softplus(-beta*x), -beta*sigmoid(-beta*x)
if method == 'ipo':
d = x - 1/(2*tau)
return d*d, 2*d
if method == 'simpo': return softplus(gamma-beta*x), -beta*sigmoid(gamma-beta*x)
if method == 'slic': return max(0., gamma-x), -1. if x < gamma else 0.
if method != 'orpo': raise ValueError('Método desconocido')
chosen = anchor+x
if chosen >= 0 or anchor >= 0: raise ValueError('Log-medias deben ser negativas')
def odds(logp): return logp - math.log(-math.expm1(logp))
difference = odds(chosen) - odds(anchor)
return softplus(-difference), -sigmoid(-difference)/(-math.expm1(chosen))
def reward_fit(n, penalty):
if n <= 0 or penalty <= 0: raise ValueError('Parámetros deben ser positivos')
lo, hi = 0., n/penalty
for _ in range(100):
mid = (lo+hi)/2
if penalty*mid - n*sigmoid(-mid) > 0: hi = mid
else: lo = mid
return (lo+hi)/2
def binary_experiment(beta, tau, n, penalty, steps=200):
dpo, ipo = 0., 0.
gap = reward_fit(n, penalty)
rows = []
for step in range(steps+1):
rows.append((step, sigmoid(-dpo), sigmoid(-ipo), dpo, ipo))
dpo -= .1*objective('dpo', dpo, beta, tau, 0.)[1]
ipo -= .1*objective('ipo', ipo, beta, tau, 0.)[1]
return {'rows':rows, 'reward_gap':gap, 'rlhf_rejected':sigmoid(-gap/beta),
'ipo_limit':sigmoid(-1/(2*tau))}
methods = ['dpo', 'ipo', 'simpo', 'slic', 'orpo']
beta, tau, gamma = 1., .5, .5
eps = 1e-6
errors = []
for method in methods:
for x in [-1.5, -.2, .2, 1.2]:
loss, derivative = objective(method, x, beta, tau, gamma)
numerical = (objective(method, x+eps, beta, tau, gamma)[0]
- objective(method, x-eps, beta, tau, gamma)[0])/(2*eps)
errors.append(abs(derivative-numerical))
assert max(errors) < 1e-8
assert objective('slic', gamma, beta, tau, gamma)[1] == 0 # subgradiente elegido
result = binary_experiment(beta, tau, 10, 1.)
gap = result['reward_gap']
assert abs(gap - 10*sigmoid(-gap)) < 1e-12
assert abs(result['rows'][-1][2]-result['ipo_limit']) < 1e-12
assert all(0 < row[1] < 1 and 0 < row[2] < 1 for row in result['rows'])
simpo_numeric = objective('simpo', .4, 2., .5, 1.)[0]
print('Errores máximos de derivada frente a diferencias finitas:', max(errors))
print('En x = 0, pérdida y derivada:', {name:objective(name, 0., beta, tau, gamma) for name in methods})
print('Ajuste RM: diferencia, derivada del objetivo:', gap, gap-10*sigmoid(-gap))
print('RLHF con RM regularizado: π rechazada:', result['rlhf_rejected'])
print('DPO e IPO, paso 200 (paso, π rechazada DPO, π rechazada IPO, logit DPO, logit IPO):', result['rows'][-1])
print('Límite IPO:', result['ipo_limit'])
print('Ejercicio SimPO:', simpo_numeric)
print('DPO se aproxima a probabilidad cero; ningún logit finito la alcanza.')KTO: binary labels and a reference point
Kahneman-Tversky Optimization by Ethayarajh and colleagues accepts individual examples labeled desirable or undesirable; it does not require each response to have a paired alternative for the same prompt. It is inspired by a value function dependent on a reference point. That inspiration does not prove the objective reproduces all of a person’s psychology.
Let and let be a reference point. One version of the per-example loss is
for a desirable or undesirable response respectively. Weights and allow the types to be treated differently, but also change the problem. In the theoretical formulation relates to KL relative to the reference; the paper estimates the term in minibatches with mismatched responses and clips the estimate to zero. The practical estimator is biased and treated as constant when calculating the gradient. A batch of size one offers no response from another example to construct that mismatch.
An isolated positive rating does not say which of two responses would be preferred side by side. Prompt distribution, class imbalance and rating collection affect the result. If converting one pair into two labels, preserve their link when splitting data and calculating uncertainty: you have not created two independent prompts.
SimPO, ORPO and the cost of removing the reference
Optimization without an explicit reference avoids a reference-policy pass or copy during fine-tuning. In exchange, the objective no longer supplies an explicit penalty for moving away from that policy. You can still measure drift, accuracy and retention with additional evaluations; removing the reference from the loss does not imply the policy stays near it.
In SimPO, write and analogously . With and margin ,
The per-token mean changes the signal compared with the sum used in DPO. shifts the logistic curve: it is not a hard bound or a finite minimum that stops updates on its own. Length normalization also does not guarantee the judge or paired dataset is free of length bias.
ORPO combines supervised loss on the chosen response with an odds-based preference term. If is the geometric mean of its token probabilities, define . Then
This is not the full sequence probability. The odds expression requires and becomes singular when ; calculate stably for . The SFT term and its normalization must be declared, because different token and sequence reductions change the effective weight of . SLiC-HF is a precursor combining a hinge ranking loss with a supervised fine-tuning term. A hinge stops pushing when it reaches its margin; the logistic flattens but still has nonzero derivative for a finite margin.
Compare methods without confusing causes
Paired objective benchmark
This cell reuses the template, splits and log-probability sums from the m20-l20 DPO cell. Full mode compares DPO, IPO, KTO, SimPO and ORPO with two configurations and three seeds per method. It selects a configuration per seed using the same validation before evaluating test. Step and search budgets are equal; token and compute budgets are recorded because objectives require different passes. KTO uses an approximate reference point from cross examples, clipped to zero and without gradient; it is not exact KL.
Set ORYON_REWARD_DIR to the reward model saved in m20-l18 and ORYON_BENCH_DIR to the output directory. ORYON_QUICK=1 reduces data, steps, configurations and seeds, loads the policy in bfloat16 and replaces the judge with Qwen2.5-0.5B-Instruct to verify the flow, with no value as a scientific comparison. Full mode uses float32 for the policy and Qwen2.5-3B-Instruct as judge; the report records precision and identity. Both judges use NF4 with double quantization and require CUDA-compatible bitsandbytes and bfloat16 compute. Results with different judges are not equivalent. ORYON_OFFLINE=1 uses cached models and requires ORYON_REWARD_JSONL. Reward model and judge are different automated signals, not human truth. The interval resamples seeds and paired prompts; no interval is reported with one seed. Inspect texts before sharing the report.
The short test runs this self-contained cell in a child process to release memory before the next lab. It requires the environment to retain source in linecache, as Jupyter or the lesson executor does, and propagates child errors. Full mode runs directly.
# La prueba corta separa el proceso para liberar memoria antes del siguiente laboratorio.
import linecache, os, subprocess, sys, tempfile
from pathlib import Path
if os.getenv('ORYON_QUICK') == '1' and os.getenv('ORYON_BENCH_CHILD') != '1':
source = ''.join(linecache.getlines(sys._getframe().f_code.co_filename))
if not source:
raise RuntimeError('No se pudo recuperar el código de la celda para aislar la prueba corta')
child_env = os.environ.copy()
child_env['ORYON_BENCH_CHILD'] = '1'
with tempfile.TemporaryDirectory(prefix='oryon-bench-') as folder:
worker = Path(folder) / 'laboratorio.py'
worker.write_text(source, encoding='utf-8')
child = subprocess.run([sys.executable, str(worker)], env=child_env, capture_output=True, text=True, encoding='utf-8', errors='replace')
print(child.stdout, end='')
if child.stderr:
sys.stderr.write(child.stderr)
if child.returncode:
raise RuntimeError(f'El laboratorio aislado terminó con código {child.returncode}')
else:
"""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
# La definición de datos, máscara y referencia anterior procede de la lección m20-l20.
from transformers import BitsAndBytesConfig
OUT=Path(os.getenv('ORYON_BENCH_DIR','./oryon-preference-benchmark'))
SEEDS=[2101] if QUICK else [2101,2102,2103]
POLICY_DTYPE=torch.bfloat16 if QUICK else torch.float32
METHODS=['dpo','ipo','kto','simpo','orpo']
GRIDS={'dpo':[.1,.3], 'ipo':[.1,.3], 'kto':[.1,.3], 'simpo':[1.,2.], 'orpo':[.1,.3]}
JUDGE='Qwen/Qwen2.5-0.5B-Instruct' if QUICK else 'Qwen/Qwen2.5-3B-Instruct'
JUDGE_REV='7ae557604adf67be50417f59c2c2f167def9a775' if QUICK else 'aa8e72537993ba99e69dfaafa59ed015b17504d1'
def objective(method,pc,pr,rc,rr,lc,lr,strength,z=None):
if method=='dpo': return F.softplus(-strength*((pc-rc)-(pr-rr)))
if method=='ipo': return ((pc-rc)-(pr-rr)-1/(2*strength))**2
if method=='kto':
if z is None: raise ValueError('KTO necesita el punto de referencia')
z=z.detach().clamp_min(0.)
return (torch.sigmoid(strength*(z-(pc-rc)))+torch.sigmoid(strength*((pr-rr)-z)))/2
if method=='simpo': return F.softplus(1.-strength*(pc/lc-pr/lr))
if method=='orpo':
c,r=pc/lc,pr/lr
if bool((c>=0).item()) or bool((r>=0).item()): raise ValueError('La log-probabilidad media debe ser negativa')
oc=c-torch.log(-torch.expm1(c)); odds_r=r-torch.log(-torch.expm1(r))
return -c+strength*F.softplus(-(oc-odds_r))
raise ValueError('Método desconocido')
def policy_model(seed):
torch.manual_seed(seed); torch.cuda.manual_seed_all(seed)
base=AutoModelForCausalLM.from_pretrained(MODEL,revision=REV,dtype=POLICY_DTYPE,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()
params=[p for name,p in model.named_parameters() if p.requires_grad and 'lora_' in name]
if not params or len(params)!=sum(p.requires_grad for p in model.parameters()): raise ValueError('Solo LoRA debe ser entrenable')
return base,model,params
def common_validation(model,rows):
scores=[]
with torch.no_grad():
for row in rows:
a,b=row['chosen_enc'],row['rejected_enc']
c=float(sequence_logp(model,a['ids'],a['start']))/a['response_tokens']
r=float(sequence_logp(model,b['ids'],b['start']))/b['response_tokens']
scores.append(1. if c>r else .5 if c==r else 0.)
return sum(scores)/len(scores)
def crossed(tok,first,other):
# Salidas del siguiente prompt con el prompt actual: estimador KTO sesgado.
row={'prompt':first['prompt'],'chosen':other['chosen'],'rejected':other['rejected']}
return encode_pair(tok,row)
def train_run(tok,train,val,method,strength,seed):
base,model,params=policy_model(seed)
opt=torch.optim.AdamW(params,lr=1e-5)
cost={'training_input_tokens':0,'training_response_tokens':0,'kto_cross_input_tokens':0,
'reference_forward_input_tokens':0,'updates':0}
if method=='kto':
mismatch=[]
for i,row in enumerate(train):
pair=None
for offset in range(1,len(train)):
try: pair=crossed(tok,row,train[(i+offset)%len(train)]); break
except ValueError: continue
if pair is None: raise ValueError('No hay respuesta cruzada que quepa sin truncar')
a,b=pair
with torch.no_grad(),model.disable_adapter():
ar=float(sequence_logp(model,a['ids'],a['start'])); br=float(sequence_logp(model,b['ids'],b['start']))
mismatch.append((a,b,ar,br))
cost['reference_forward_input_tokens']+=len(a['ids'])+len(b['ids'])
for step in range(UPDATES):
row=train[step%len(train)]; a,b=row['chosen_enc'],row['rejected_enc']
opt.zero_grad(set_to_none=True)
pc=sequence_logp(model,a['ids'],a['start']); pr=sequence_logp(model,b['ids'],b['start'])
z=None
if method=='kto':
ca,cb,ra,rb=mismatch[step%len(train)]
with torch.no_grad():
z=((sequence_logp(model,ca['ids'],ca['start'])-ra)+(sequence_logp(model,cb['ids'],cb['start'])-rb))/2
cost['kto_cross_input_tokens']+=len(ca['ids'])+len(cb['ids'])
loss=objective(method,pc,pr,row['ref_chosen'],row['ref_rejected'],a['response_tokens'],b['response_tokens'],strength,z)
if not torch.isfinite(loss): raise ValueError('Pérdida no finita')
loss.backward(); torch.nn.utils.clip_grad_norm_(params,1.); opt.step()
cost['training_input_tokens']+=len(a['ids'])+len(b['ids'])
cost['training_response_tokens']+=a['response_tokens']+b['response_tokens']; cost['updates']+=1
validation=common_validation(model,val)
cost['validation_input_tokens']=sum(len(r['chosen_enc']['ids'])+len(r['rejected_enc']['ids']) for r in val)
directory=OUT/f'{method}-{strength:g}-{seed}'; directory.mkdir(parents=True,exist_ok=True)
model.save_pretrained(directory,safe_serialization=True)
result={'method':method,'strength':strength,'seed':seed,'validation_accuracy':validation,'cost':cost,
'adapter':directory.name,'adapter_sha256':file_hash(directory/'adapter_model.safetensors')}
del pc,pr,loss,opt,model,base,params; gc.collect(); torch.cuda.empty_cache()
return result
def sample_one(model,tok,row,seed):
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 sin espacio para generar')
local=(seed+int(row['prompt_hash'][:16],16))%(2**63-1)
generator=torch.Generator(device='cuda').manual_seed(local); tokens=[]
end={tok.convert_tokens_to_ids('<|im_end|>'),tok.convert_tokens_to_ids('<|endoftext|>')}
with torch.inference_mode():
for _ in range(NEW_TOKENS):
x=torch.tensor([prefix+tokens],device='cuda')
logits=model(input_ids=x,use_cache=False).logits[0,-1].float()
token=int(torch.multinomial(logits.softmax(-1),1,generator=generator)); tokens.append(token)
if token in end: break
return {'prompt_hash':row['prompt_hash'],'prompt':row['prompt'],'tokens':tokens,
'generation_input_tokens':len(tokens)*len(prefix)+len(tokens)*(len(tokens)-1)//2,
'text':tok.decode(tokens,skip_special_tokens=True,clean_up_tokenization_spaces=False),
'ended_with':tok.convert_ids_to_tokens(tokens[-1]) if tokens[-1] in end else 'límite','seed':local}
def rollout_all(tok,test,chosen):
samples=[]
for seed in SEEDS:
base,model,_=policy_model(seed)
with model.disable_adapter():
for row in test:
item=sample_one(model,tok,row,seed); item.update({'method':'base','training_seed':seed}); samples.append(item)
del model,base; gc.collect(); torch.cuda.empty_cache()
for run in chosen:
base=AutoModelForCausalLM.from_pretrained(MODEL,revision=REV,dtype=POLICY_DTYPE,local_files_only=OFFLINE).to('cuda')
model=PeftModel.from_pretrained(base,OUT/run['adapter']).eval()
for row in test:
item=sample_one(model,tok,row,run['seed']); item.update({'method':run['method'],'training_seed':run['seed']}); samples.append(item)
del model,base; gc.collect(); torch.cuda.empty_cache()
return samples
def reward_all(samples):
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('Huellas del RM incoherentes')
snapshot=Path(snapshot_download(meta['model'],revision=meta['revision'],local_files_only=OFFLINE,allow_patterns=['*.safetensors']))
if hash_files(snapshot)!=meta['weights_sha256']: raise ValueError('Base del RM distinta')
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()
calls=0; input_tokens=0
with torch.inference_mode():
for item in samples:
try:
if any(s and s in item['prompt']+item['text'] for s in tok.all_special_tokens): raise ValueError('Grafía de control')
ids=unpack_ids(tok.apply_chat_template([{'role':'user','content':item['prompt']},{'role':'assistant','content':item['text']}],tokenize=True,add_generation_prompt=False))
if len(ids)>meta['max_context']: raise ValueError('Respuesta excede contexto del RM')
x=torch.tensor([ids],device='cuda'); calls+=1; input_tokens+=len(ids)
h=model(input_ids=x,attention_mask=torch.ones_like(x),use_cache=False).last_hidden_state[0,-1].float()
value=float((weight@h).item())
if not math.isfinite(value): raise ValueError('Recompensa no finita')
item['reward']=value
except ValueError as exc: item['reward']=None; item['reward_unavailable']=str(exc)
del model,base,weight,tok; gc.collect(); torch.cuda.empty_cache()
return {'metadata_sha256':file_hash(REWARD/'reward-meta.json'),'head_sha256':meta['head_sha256'],
'adapter_sha256':meta['adapter_sha256'],'forward_calls':calls,'input_tokens':input_tokens}
def judge_all(samples):
if not torch.cuda.is_bf16_supported(): raise RuntimeError('El juez necesita CUDA con bfloat16')
try: import bitsandbytes as bnb
except ImportError as exc: raise RuntimeError('Instala bitsandbytes compatible con CUDA para el juez NF4') from exc
tok=AutoTokenizer.from_pretrained(JUDGE,revision=JUDGE_REV,local_files_only=OFFLINE)
labels=[tok.encode(c,add_special_tokens=False) for c in ('A','B')]
if any(len(x)!=1 for x in labels) or labels[0][0]==labels[1][0]: raise ValueError('El juez no tiene A/B de un token distinto')
snapshot=Path(snapshot_download(JUDGE,revision=JUDGE_REV,local_files_only=OFFLINE,allow_patterns=['*.safetensors']))
weights=hash_files(snapshot)
if not weights: raise ValueError('No hay pesos safetensors del juez')
quant=BitsAndBytesConfig(load_in_4bit=True,bnb_4bit_quant_type='nf4',bnb_4bit_use_double_quant=True,
bnb_4bit_compute_dtype=torch.bfloat16)
model=AutoModelForCausalLM.from_pretrained(JUDGE,revision=JUDGE_REV,dtype=torch.bfloat16,
quantization_config=quant,local_files_only=OFFLINE,device_map={'':0}).eval()
layers=[m for m in model.modules() if isinstance(m,bnb.nn.Linear4bit)]
if not layers or any(m.weight.quant_state is None or m.weight.quant_state.quant_type!='nf4'
or not m.weight.quant_state.nested for m in layers):
raise ValueError('El juez no usa NF4 con doble cuantización')
layer_count=len(layers)
base={(x['training_seed'],x['prompt_hash']):x for x in samples if x['method']=='base'}
calls=0; input_tokens=0
with torch.inference_mode():
for item in samples:
if item['method']=='base': continue
baseline=base[(item['training_seed'],item['prompt_hash'])]['text']; logits=[]
try:
for first,second in ((item['text'],baseline),(baseline,item['text'])):
content=('Choose the better answer to the user request. Reply with A or B only.\n'
'User request: '+item['prompt']+'\nAnswer A:\n'+first+'\nAnswer B:\n'+second)
if any(s and s in content for s in tok.all_special_tokens): raise ValueError('Grafía de control')
ids=unpack_ids(tok.apply_chat_template([{'role':'user','content':content}],tokenize=True,add_generation_prompt=True))
if len(ids)>1024: raise ValueError('Par excede contexto del juez')
calls+=1; input_tokens+=len(ids)
p=model(input_ids=torch.tensor([ids],device='cuda'),use_cache=False).logits[0,-1].float()
logits.append(float(p[labels[0][0]]-p[labels[1][0]]))
if not math.isfinite(logits[-1]): raise ValueError('Salida no finita del juez')
item['judge_margin']=(logits[0]-logits[1])/2
item['judge_order_logits']=logits
except ValueError as exc: item['judge_margin']=None; item['judge_unavailable']=str(exc)
del layers,model,tok; gc.collect(); torch.cuda.empty_cache()
return weights,calls,input_tokens,layer_count,str(bnb.__version__)
def paired_bootstrap(samples,method,metric='judge_margin',iterations=1000):
ref={(x['training_seed'],x['prompt_hash']):x for x in samples if x['method']=='dpo'}
other={(x['training_seed'],x['prompt_hash']):x for x in samples if x['method']==method}
keys=sorted(k for k in ref.keys() & other.keys() if ref[k].get(metric) is not None and other[k].get(metric) is not None)
differences={k:other[k][metric]-ref[k][metric] for k in keys}
seed_ids=sorted({k[0] for k in keys}); prompt_ids=sorted({k[1] for k in keys})
all_values=list(differences.values())
if not all_values: return {'mean':None,'interval':None,'seeds':0,'paired':0}
average=sum(all_values)/len(all_values)
if len(seed_ids)<2: return {'mean':average,'interval':None,'seeds':len(seed_ids),'paired':len(all_values)}
randomizer=random.Random(210121); estimates=[]
for _ in range(iterations):
drawn_seeds=[randomizer.choice(seed_ids) for _ in seed_ids]
drawn_prompts=[randomizer.choice(prompt_ids) for _ in prompt_ids]
sampled=[differences[(s,p)] for s in drawn_seeds for p in drawn_prompts if (s,p) in differences]
if sampled: estimates.append(sum(sampled)/len(sampled))
if not estimates: return {'mean':average,'interval':None,'seeds':len(seed_ids),'paired':len(all_values)}
return {'mean':average,'interval':[float(x) for x in np.quantile(estimates,[.025,.975])],
'seeds':len(seed_ids),'paired':len(all_values),'resamples':len(estimates),'bootstrap_seed':210121,
'resampling':'semillas y prompts cruzados; mismos prompts remuestreados entre semillas'}
def summarize_samples(samples):
summary={}
for method in ['base']+METHODS:
rows=[x for x in samples if x['method']==method]
rewards=[x['reward'] for x in rows if x.get('reward') is not None]
margins=[x['judge_margin'] for x in rows if x.get('judge_margin') is not None]
summary[method]={'samples':len(rows),'mean_tokens':sum(len(x['tokens']) for x in rows)/len(rows) if rows else None,
'reward_mean':sum(rewards)/len(rewards) if rewards else None,'reward_scored':len(rewards),
'judge_mean_margin':sum(margins)/len(margins) if margins else None,
'judge_wins_with_ties_half':sum(1 if x>0 else .5 if x==0 else 0 for x in margins)/len(margins) if margins else None,
'judge_scored':len(margins)}
return summary
def main():
if not torch.cuda.is_available(): raise RuntimeError('El benchmark requiere CUDA')
OUT.mkdir(parents=True,exist_ok=True)
random.seed(2101); np.random.seed(2101); torch.manual_seed(2101); torch.cuda.manual_seed_all(2101)
prior_path=REWARD/'reward-report.json'; prior=json.loads(prior_path.read_text(encoding='utf-8'))
tok=AutoTokenizer.from_pretrained(MODEL,revision=REV,local_files_only=OFFLINE)
train,val,test=collect_pairs(tok,prior)
snapshot=Path(snapshot_download(MODEL,revision=REV,local_files_only=OFFLINE,allow_patterns=['*.safetensors','tokenizer.json','tokenizer_config.json']))
weights=hash_files(snapshot); tokenizers={n:file_hash(snapshot/n) for n in ('tokenizer.json','tokenizer_config.json')}
if not weights: raise ValueError('Faltan pesos base')
reference_input_tokens=sum(len(r['chosen_enc']['ids'])+len(r['rejected_enc']['ids']) for r in train+val+test)
base,model,_=policy_model(2101)
reference_scores(model,train+val+test)
del model,base; gc.collect(); torch.cuda.empty_cache()
runs=[]
for seed in SEEDS:
for method in METHODS:
for strength in (GRIDS[method][:1] if QUICK else GRIDS[method]):
runs.append(train_run(tok,train,val,method,strength,seed))
print(method,'semilla',seed,'hiperparámetro',strength,'validación',runs[-1]['validation_accuracy'],flush=True)
selected=[]
for seed in SEEDS:
for method in METHODS:
candidates=[r for r in runs if r['seed']==seed and r['method']==method]
selected.append(max(candidates,key=lambda r:r['validation_accuracy']))
samples=rollout_all(tok,test,selected)
reward=reward_all(samples); judge_weights,judge_calls,judge_tokens,judge_layers,bnb_version=judge_all(samples)
intervals={method:paired_bootstrap(samples,method) for method in METHODS if method!='dpo'}
reward_intervals={method:paired_bootstrap(samples,method,'reward') for method in METHODS if method!='dpo'}
source=({'kind':'JSONL local sin verificar','sha256':file_hash(LOCAL)} if LOCAL else {'kind':'Hugging Face','id':DATA,'revision':DATA_REV})
report={'quick':QUICK,'seeds':SEEDS,'model':MODEL,'revision':REV,'policy_dtype':str(POLICY_DTYPE),'weights_sha256':weights,'tokenizer_sha256':tokenizers,
'source':source,'reward':reward,'judge':{'id':JUDGE,'revision':JUDGE_REV,'weights_sha256':judge_weights,
'quantization':'NF4 con doble cuantización; cómputo bfloat16','nf4_layers':judge_layers,
'bitsandbytes_version':bnb_version,'protocol':'A/B en ambos órdenes; margen de logits, no verdad humana'},
'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]},
'sampling':{'temperature':1,'top_k':None,'top_p':None,'max_new_tokens':NEW_TOKENS,'shared_prompt_seed':True},
'shared_cost':{'reference_input_tokens':reference_input_tokens,
'reference_note':'Precomputación compartida para todos; los métodos sin referencia no necesitan este coste.',
'generated_tokens':sum(len(s['tokens']) for s in samples),
'generation_input_tokens':sum(s['generation_input_tokens'] for s in samples),
'judge_forward_calls':judge_calls,'judge_input_tokens':judge_tokens,
'note':'Contadores de tokens y llamadas, no FLOPs ni tiempo medidos.'},
'runs':runs,'selected':selected,'samples':samples,'summary':summarize_samples(samples),
'paired_judge_vs_dpo':intervals,'paired_reward_vs_dpo':reward_intervals,
'validation_rule':'exactitud de log-probabilidad media de elegida frente a rechazada; desempate por primer parámetro',
'limits':'Una muestra por prompt y semilla; juez automático sesgado, test pequeño y sin control de contaminación aproximada. Pasos iguales no implican FLOPs iguales; KTO usa muestras cruzadas y stop-gradient.'}
write_json(OUT/'benchmark-report.json',report)
print('Resumen:',json.dumps(report['summary'],ensure_ascii=False),flush=True)
print('Informe:',OUT/'benchmark-report.json','comparaciones pareadas:',intervals,flush=True)
if __name__=='__main__': main()npm run lab and open the connection link.For a controlled comparison, fix initial model, prompt splits, evaluation, hardware conditions and search budget. Tune each method separately with the same rule and number of trials. Use multiple seeds, retain every run and report training as well as generation, labeling and search costs. A reference-free method can save memory during fine-tuning and shift other costs to evaluation or data preparation.
With the same test prompts, compare paired differences by prompt. If multiple responses or comparisons share a prompt, they are not independent observations: resample prompts and consider a hierarchical structure if also reflecting seed variation. A bootstrap interval describes uncertainty under the selected resampling procedure; it does not correct biased labels or prior contamination. Controlled comparisons and the nonparametric bootstrap develop these choices.
Learn from the current policy
Iterative optimization repeats generation, judgment and fine-tuning. In each round freeze a checkpoint, generate candidates for training prompts, collect preferences and train the next policy. As the response distribution changes, the new batch can cover errors old pairs do not show; it can also amplify judge biases or lose diversity. A batch generated at the beginning of a round becomes progressively off-policy as its weights are updated.
Guo and colleagues studied online AI feedback by generating policy candidates and using a model as judge. In self-rewarding, Yuan and colleagues explore having the model itself judge responses and participate in successive DPO rounds. Sharing generator and judge introduces a possible self-reinforcing loop; record which checkpoint judges, compare another criterion and hold out prompts that do not participate in selection.
The figure includes a short-run report with a float32 policy, 3B judge, one seed, three rounds of one update and two test prompts. The first round ran alongside initialization; the next two continued from their checkpoints in separate processes to respect shared memory. The rates do not establish that the method improves. The report SHA-256 is 994debe5602b6851ec4a00c45330e212e8365f1fb265464b67495d615a927e17.
Preparing measured rounds.
The cycle starts from m20-l20’s initial DPO checkpoint and performs three rounds: sample two responses from the current policy per prompt, compare them with a Qwen2.5 judge in NF4 with double quantization, and update LoRA with DPO. The full judge is 3B and QUICK uses 0.5B. The judge evaluates each pair in both orders; its A/B logit difference is averaged with corrected signs. Ties and inputs that do not fit are recorded and not converted into labels. The DPO reference stays fixed: the base with the adapter disabled. After every update the reference distribution is checked again for changes.
To retain the DPO mask, training pairs must naturally end in <|im_end|> and their tokens must be recovered exactly on decoding and re-encoding. Attempts and generation tokens are recorded, so this conditioned selection is not presented as an unfiltered sample. If a round does not obtain valid pairs, the program retains previous progress and terminates without inventing metrics. The budget includes supervised tokens, judge calls and input tokens, evaluations and generations; these counts do not imply equal cost per token across models.
Test prompts come from the m20-l18 reward-model holdout and are excluded by exact hash from cycle training and validation. After each round, a separate m20-l18 reward model compares the current response with the initial response on the same prompt; a tie counts half a point. Generated length and word-based distinct-2 are also measured. Correlation between length difference and evaluator margin is descriptive and may be undefined. Judge and evaluator are models, not human arbiters, and may share biases; their agreement does not prove general quality. The control uses the same per-prompt seeds across checkpoints and records denominators and unscorable examples.
Install torch, transformers, peft, datasets, huggingface_hub, safetensors and bitsandbytes compatible with CUDA and bfloat16. Set ORYON_DPO_DIR and ORYON_REWARD_DIR to locate previous lessons’ artifacts, and ORYON_ITERATIVE_DIR to save outputs. ORYON_DPO_BETA must match the initial checkpoint. ORYON_QUICK=1 still runs three rounds, with two training prompts, two test prompts, one update per round, bfloat16 policy and 0.5B judge; normal mode uses 64 training prompts, 16 test prompts, 64 updates per round, float32 policy and 3B judge. The report records precision and judge identity. The public dataset is queried at the fixed UltraFeedback revision; offline, supply ORYON_REWARD_JSONL and ORYON_OFFLINE=1 with snapshots already cached. For the foundation of online data see Direct Language Model Alignment from Online AI Feedback and DPO. Monotonic improvement is not necessarily expected.
"""Tres rondas DPO iterativo con juez NF4 y evaluación separada."""
import gc, hashlib, json, math, os, random, re
from collections import defaultdict
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 PeftModel
from safetensors.torch import load_file
from torch.nn import functional as F
from transformers import AutoModel, AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
QUICK=os.getenv('ORYON_QUICK')=='1'
POLICY_DTYPE=torch.bfloat16 if QUICK else torch.float32
OFFLINE=os.getenv('ORYON_OFFLINE')=='1'
DPO=Path(os.getenv('ORYON_DPO_DIR','./oryon-dpo'))
REWARD=Path(os.getenv('ORYON_REWARD_DIR','./oryon-reward'))
OUT=Path(os.getenv('ORYON_ITERATIVE_DIR','./oryon-iterative'))
LOCAL=os.getenv('ORYON_REWARD_JSONL','')
MODEL='Qwen/Qwen2.5-0.5B-Instruct'
REV='7ae557604adf67be50417f59c2c2f167def9a775'
JUDGE='Qwen/Qwen2.5-0.5B-Instruct' if QUICK else 'Qwen/Qwen2.5-3B-Instruct'
JUDGE_REV='7ae557604adf67be50417f59c2c2f167def9a775' if QUICK else 'aa8e72537993ba99e69dfaafa59ed015b17504d1'
DATA='HuggingFaceH4/ultrafeedback_binarized'
DATA_REV='3949bf5f8c17c394422ccfab0c31ea9c20bdeb85'
SEED=2121; BETA=float(os.getenv('ORYON_DPO_BETA','.1')); MAX_CONTEXT=384; ROUNDS=3
if not math.isfinite(BETA) or BETA<=0: raise ValueError('ORYON_DPO_BETA debe ser finito y positivo')
N_TRAIN,N_VAL,N_TEST=(2,2,2) if QUICK else (64,16,16)
STEPS_PER_ROUND=1 if QUICK else 64
MAX_NEW=24 if QUICK else 128
MAX_ATTEMPTS=12 if QUICK else 24
torch.set_num_threads(1)
# Mismas funciones de la celda DPO anterior.
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 write_json(path,value): path.write_text(json.dumps(value,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 source():
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('Fija ORYON_REWARD_JSONL para trabajar sin red')
yield from load_dataset(DATA,split='train_prefs',revision=DATA_REV,streaming=True)
def prompts(tok):
previous=json.loads((REWARD/'reward-report.json').read_text(encoding='utf-8'))
test=[]; seen=set()
with (REWARD/'test-prompts.jsonl').open(encoding='utf-8') as f:
for line in f:
row=json.loads(line); key=sha(normal(row['prompt']))
if row['prompt_id']!=key or key not in previous['test_prompt_hashes'] or row['split']!='test_prefs':
raise ValueError('El test no coincide con el informe reward')
if key in previous['train_prompt_hashes'] or key in previous['validation_prompt_hashes']:
raise ValueError('El test coincide con entrenamiento o validación del evaluador')
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: continue
if key not in seen:
seen.add(key); test.append({'prompt':row['prompt'],'prompt_hash':key})
if len(test)==N_TEST: break
if len(test)!=N_TEST: raise ValueError('Faltan prompts test del reward model')
blocked=set(previous['test_prompt_hashes']); train=[]; val=[]; seen=set()
for row in source():
chosen=row.get('chosen')
if not isinstance(chosen,list) or len(chosen)!=2 or not isinstance(chosen[0],dict): continue
q=chosen[0].get('content')
if not isinstance(q,str) or not q.strip() or chosen[0].get('role')!='user': continue
if any(s and s in q for s in tok.all_special_tokens): continue
key=sha(normal(q))
if key in blocked or key in seen: continue
prefix=unpack_ids(tok.apply_chat_template([{'role':'user','content':q}],tokenize=True,add_generation_prompt=True))
if len(prefix)+MAX_NEW>MAX_CONTEXT: continue
seen.add(key); group=val if int(key[:8],16)%10==0 else train
if len(group)<(N_VAL if group is val else N_TRAIN): group.append({'prompt':q,'prompt_hash':key})
if len(train)==N_TRAIN and len(val)==N_VAL: break
if len(train)!=N_TRAIN or len(val)!=N_VAL: raise ValueError('No hay suficientes prompts distintos')
assert not ({r['prompt_hash'] for r in train}&{r['prompt_hash'] for r in val})
assert not ({r['prompt_hash'] for r in train+val}&blocked)
return train,val,test
def policy(path, trainable=False):
base=AutoModelForCausalLM.from_pretrained(MODEL,revision=REV,dtype=POLICY_DTYPE,
local_files_only=OFFLINE).to('cuda')
base.config.use_cache=False
return PeftModel.from_pretrained(base,path,is_trainable=trainable).eval()
def sample(model,tok,row,seed):
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: raise ValueError('El prompt no deja espacio al horizonte')
end=tok.convert_tokens_to_ids('<|im_end|>'); other=tok.convert_tokens_to_ids('<|endoftext|>')
generator=torch.Generator(device='cuda').manual_seed(seed)
tokens=[]
with torch.no_grad():
for _ in range(MAX_NEW):
logits=model(input_ids=torch.tensor([prefix+tokens],device='cuda'),use_cache=False).logits[0,-1].float()
token=int(torch.multinomial(logits.softmax(-1),1,generator=generator).item()); tokens.append(token)
if token in (end,other): break
raw=tok.decode(tokens[:-1] if tokens[-1] in (end,other) else tokens,skip_special_tokens=False,clean_up_tokenization_spaces=False)
return {'tokens':tokens,'text':raw,'ended':tokens[-1]==end,'seed':seed}
def valid_train_sample(tok,row,sample):
eos=tok.convert_tokens_to_ids('<|im_end|>')
if not sample['ended'] or not sample['text'].strip() or any(t in tok.all_special_ids for t in sample['tokens'][:-1]): return False
candidate={'prompt':row['prompt'],'chosen':sample['text'],'rejected':sample['text']}
try: enc,_=encode_pair(tok,candidate)
except ValueError: return False
return enc['ids'][enc['start']:]==sample['tokens'] and sample['tokens'][-1]==eos
def generate_round(path,tok,train,round_index):
model=policy(path); candidates=[]; attempts=0; generated_tokens=0
for row in train:
options=[]
for attempt in range(MAX_ATTEMPTS):
seed=(SEED+round_index*100000+int(row['prompt_hash'][:16],16)+attempt)%(2**63-1)
result=sample(model,tok,row,seed); attempts+=1; generated_tokens+=len(result['tokens'])
if not valid_train_sample(tok,row,result) or any(result['tokens']==o['tokens'] for o in options): continue
options.append(result)
if len(options)==2: break
if len(options)==2: candidates.append({**row,'samples':options})
del model; gc.collect(); torch.cuda.empty_cache()
return candidates,{'attempts':attempts,'generated_tokens':generated_tokens,
'requested_train_prompts':len(train),'pairs_with_two_valid_samples':len(candidates)}
def generate_eval(path,tok,test):
model=policy(path); rows=[]
for row in test:
seed=(SEED+900000+int(row['prompt_hash'][:16],16))%(2**63-1)
rows.append({**row,'sample':sample(model,tok,row,seed)})
del model; gc.collect(); torch.cuda.empty_cache()
return rows
def judge_pairs(rows):
import bitsandbytes as bnb
tok=AutoTokenizer.from_pretrained(JUDGE,revision=JUDGE_REV,local_files_only=OFFLINE)
ids=[tok.encode(c,add_special_tokens=False) for c in ('A','B')]
if any(len(x)!=1 for x in ids) or ids[0]==ids[1]: raise ValueError('A y B deben ser tokens individuales distintos')
quant=BitsAndBytesConfig(load_in_4bit=True,bnb_4bit_quant_type='nf4',
bnb_4bit_use_double_quant=True,bnb_4bit_compute_dtype=torch.bfloat16)
model=AutoModelForCausalLM.from_pretrained(JUDGE,revision=JUDGE_REV,local_files_only=OFFLINE,
quantization_config=quant,dtype=torch.bfloat16,device_map={'':0}).eval()
layers=[m for m in model.modules() if isinstance(m,bnb.nn.Linear4bit)]
if not layers or any(m.weight.quant_state is None or m.weight.quant_state.quant_type!='nf4'
or not m.weight.quant_state.nested for m in layers):
raise ValueError('El juez no está cuantizado con NF4 y doble cuantización')
snap=Path(snapshot_download(JUDGE,revision=JUDGE_REV,local_files_only=OFFLINE,allow_patterns=['*.safetensors']))
weight_hashes=hashes(snap)
if not weight_hashes: raise ValueError('No se encontraron pesos del juez')
labelled=[]; unavailable=defaultdict(int); calls=0; judge_tokens=0; ties=0
with torch.no_grad():
for row in rows:
a,b=row['samples']; margins=[]
for first,second in ((a,b),(b,a)):
prompt=('Choose the better response to the user request. Reply with A or B only.\nRequest: '
+row['prompt']+'\nAnswer A:\n'+first['text']+'\nAnswer B:\n'+second['text'])
x=unpack_ids(tok.apply_chat_template([{'role':'user','content':prompt}],tokenize=True,add_generation_prompt=True))
if len(x)>1024: break
logits=model(input_ids=torch.tensor([x],device='cuda'),use_cache=False).logits[0,-1].float()
margins.append(float(logits[ids[0][0]]-logits[ids[1][0]])); calls+=1; judge_tokens+=len(x)
if len(margins)!=2: unavailable['contexto del juez']+=1; continue
combined=(margins[0]-margins[1])/2
if not math.isfinite(combined): raise ValueError('Juicio no finito')
if combined==0: ties+=1; continue
chosen,rejected=(a,b) if combined>0 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'],
'logits_ab':margins[0],'logits_ba':margins[1]})
layer_count=len(layers)
del layers,model,tok; gc.collect(); torch.cuda.empty_cache()
return labelled,{'calls':calls,'input_tokens':judge_tokens,'ties':ties,'unscored':dict(unavailable),'nf4_layers':layer_count,
'weights_sha256':weight_hashes,'id':JUDGE,'revision':JUDGE_REV}
def train_round(path, tok, rows, round_index):
if not rows: raise ValueError('Sin pares válidos, no se puede entrenar la ronda')
model=policy(path,trainable=True)
named=[(n,p) for n,p in model.named_parameters() if p.requires_grad]
if not named or any('lora_' not in n for n,_ in named): raise ValueError('Solo LoRA debe ser entrenable')
for row in rows:
a,b=encode_pair(tok,row)
if a['ids'][a['start']:]!=row['chosen_tokens'] or b['ids'][b['start']:]!=row['rejected_tokens']:
raise ValueError('La respuesta tokenizada no coincide con la muestra')
row['chosen_enc'],row['rejected_enc']=a,b
with torch.no_grad(),model.disable_adapter():
row['ref_chosen']=float(sequence_logp(model,a['ids'],a['start']))
row['ref_rejected']=float(sequence_logp(model,b['ids'],b['start']))
def reference_probe():
a=rows[0]['chosen_enc']; x=torch.tensor([a['ids']],device='cuda')
with torch.no_grad(),model.disable_adapter():
logits=model(input_ids=x,use_cache=False).logits[0,a['start']-1:-1].float()
return logits.log_softmax(-1).cpu()
before=reference_probe(); optimizer=torch.optim.AdamW([p for _,p in named],lr=1e-5)
log=[]; processed=0; supervised=0
for step in range(STEPS_PER_ROUND):
row=rows[step%len(rows)]; a,b=row['chosen_enc'],row['rejected_enc']
optimizer.zero_grad(set_to_none=True)
ca=sequence_logp(model,a['ids'],a['start']); cb=sequence_logp(model,b['ids'],b['start'])
loss=dpo_loss(ca,cb,row['ref_chosen'],row['ref_rejected'],BETA)
if not torch.isfinite(loss): raise ValueError('La pérdida DPO no es finita')
loss.backward(); torch.nn.utils.clip_grad_norm_([p for _,p in named],1.); optimizer.step()
processed+=len(a['ids'])+len(b['ids']); supervised+=a['response_tokens']+b['response_tokens']
log.append(float(loss.detach()))
after=reference_probe(); drift=float((after-before).abs().max())
if not torch.allclose(after,before,atol=2e-5,rtol=2e-5): raise ValueError('La referencia base ha cambiado')
output=OUT/f'checkpoint-{round_index}'
model.save_pretrained(output,safe_serialization=True); tok.save_pretrained(output)
adapter_hash=file_hash(output/'adapter_model.safetensors')
del optimizer,model; gc.collect(); torch.cuda.empty_cache()
return output,{'steps':STEPS_PER_ROUND,'processed_tokens':processed,'supervised_tokens':supervised,
'loss':log,'reference_max_logprob_change':drift,'adapter_sha256':adapter_hash}
def distinct2(rows):
bigrams=[]
for row in rows:
words=re.findall(r'\w+',row['sample']['text'].casefold(),flags=re.UNICODE)
bigrams.extend(zip(words,words[1:]))
return len(set(bigrams))/len(bigrams) if bigrams else None
def evaluate_independent(base_rows, 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('Huellas del evaluador reward no coinciden')
snap=Path(snapshot_download(meta['model'],revision=meta['revision'],local_files_only=OFFLINE,allow_patterns=['*.safetensors']))
if hashes(snap)!=meta['weights_sha256']: raise ValueError('Pesos del evaluador reward diferentes')
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()
calls=0
def score(prompt,answer):
nonlocal calls
if any(s and s in prompt+answer for s in tok.all_special_tokens): raise ValueError('Grafía de control')
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 de contexto del evaluador')
x=torch.tensor([ids],device='cuda')
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('Puntuación no finita')
return value
if [x['prompt_hash'] for x in base_rows]!=[x['prompt_hash'] for x in rows]: raise ValueError('Prompts de evaluación distintos')
valid=[]; skipped=defaultdict(int)
with torch.no_grad():
for base_row,row in zip(base_rows,rows):
try:
a=score(row['prompt'],base_row['sample']['text'])
b=score(row['prompt'],row['sample']['text'])
except ValueError as exc:
skipped[str(exc)]+=1; continue
delta=b-a; lengths=len(row['sample']['tokens'])-len(base_row['sample']['tokens'])
valid.append({'prompt_hash':row['prompt_hash'],'reference_score':a,'current_score':b,
'margin':delta,'token_length_difference':lengths})
wins=sum(1. if r['margin']>0 else .5 if r['margin']==0 else 0. for r in valid)
length=np.asarray([x['token_length_difference'] for x in valid],float)
margins=np.asarray([x['margin'] for x in valid],float)
corr=float(np.corrcoef(length,margins)[0,1]) if len(valid)>1 and length.std()>0 and margins.std()>0 else None
report={'win_rate':wins/len(valid) if valid else None,'scored_pairs':len(valid),'requested_pairs':len(rows),
'unscored':dict(skipped),'judge_calls':calls,'length_margin_pearson':corr,'pairs':valid,
'evaluator':{'model':meta['model'],'revision':meta['revision'],'adapter_sha256':meta['adapter_sha256'],
'head_sha256':meta['head_sha256']}}
del model,base,weight,tok; gc.collect(); torch.cuda.empty_cache()
return report
def round_metrics(round_index, base_rows, eval_rows):
evaluation=evaluate_independent(base_rows,eval_rows)
return {'round':round_index,'win_rate':evaluation['win_rate'],
'win_rate_denominator':evaluation['scored_pairs'],
'requested_evaluations':evaluation['requested_pairs'],
'mean_generated_tokens':sum(len(r['sample']['tokens']) for r in eval_rows)/len(eval_rows),
'distinct2':distinct2(eval_rows),'length_margin_pearson':evaluation['length_margin_pearson'],
'evaluator':evaluation,'samples':eval_rows}
def main():
if not torch.cuda.is_available() or not torch.cuda.is_bf16_supported():
raise RuntimeError('Se necesita CUDA con bfloat16 para el juez NF4')
try: import bitsandbytes
except ImportError as exc: raise RuntimeError('Instala bitsandbytes compatible con CUDA') from exc
OUT.mkdir(parents=True,exist_ok=True)
random.seed(SEED); np.random.seed(SEED); torch.manual_seed(SEED); torch.cuda.manual_seed_all(SEED)
initial=DPO/'checkpoint-0'; initial_manifest=json.loads((initial/'manifest.json').read_text(encoding='utf-8'))
if (initial_manifest['model']!=MODEL or initial_manifest['revision']!=REV or initial_manifest['beta']!=BETA
or initial_manifest['adapter_sha256']!=file_hash(initial/'adapter_model.safetensors')):
raise ValueError('Checkpoint inicial DPO incompatible')
snap=Path(snapshot_download(MODEL,revision=REV,local_files_only=OFFLINE,allow_patterns=['*.safetensors']))
if hashes(snap)!=initial_manifest['base_weights_sha256']: raise ValueError('Pesos de la política distintos')
tok=AutoTokenizer.from_pretrained(initial,local_files_only=True)
original_tok=AutoTokenizer.from_pretrained(MODEL,revision=REV,local_files_only=OFFLINE)
if (tok.get_vocab()!=original_tok.get_vocab() or tok.special_tokens_map!=original_tok.special_tokens_map
or tok.chat_template!=original_tok.chat_template or not tok.is_fast or not original_tok.is_fast
or tok.backend_tokenizer.to_str()!=original_tok.backend_tokenizer.to_str()):
raise ValueError('Tokenizador del checkpoint distinto del modelo original')
del original_tok
train,val,test=prompts(tok)
initial_eval=generate_eval(initial,tok,test)
first=round_metrics(0,initial_eval,initial_eval)
first['eval_generated_tokens']=sum(len(x['sample']['tokens']) for x in initial_eval)
data={'id':'JSONL local, procedencia no verificada' if LOCAL else DATA,
'revision':None if LOCAL else DATA_REV,'sha256':file_hash(LOCAL) if LOCAL else None}
report={'model':MODEL,'revision':REV,'quick':QUICK,'policy_dtype':str(POLICY_DTYPE),'seed':SEED,'beta':BETA,'data':data,
'initial_checkpoint_sha256':initial_manifest['adapter_sha256'],
'splits':{'train':[r['prompt_hash'] for r in train], 'validation':[r['prompt_hash'] for r in val],
'test':[r['prompt_hash'] for r in test]},
'configuration':{'rounds':ROUNDS,'steps_per_round':STEPS_PER_ROUND,'max_new_tokens':MAX_NEW,
'attempts_per_prompt':MAX_ATTEMPTS,'temperature':1,'top_k':None,'top_p':None,
'reference':'base original con adaptador desactivado','evaluator':'reward model l18'},
'rounds':[first], 'status':'incompleto',
'limitations':f'El juez {JUDGE} y el evaluador RM son modelos, no verdad humana. Una semilla y pocos prompts no prueban tendencias ni causalidad por longitud.'}
output=OUT/'iterative-report.json'; write_json(output,report)
current=initial
for r in range(1,ROUNDS+1):
candidates,generation=generate_round(current,tok,train,r)
write_json(OUT/f'round-{r}-candidates.json',{'rows':candidates,'generation':generation})
if not candidates: raise ValueError('La ronda no obtuvo dos respuestas válidas en ningún prompt')
labelled,judging=judge_pairs(candidates)
write_json(OUT/f'round-{r}-preferences.json',{'pairs':labelled,'judging':judging})
if not labelled: raise ValueError('El juez no produjo pares válidos para la ronda')
current,training=train_round(current,tok,labelled,r)
eval_rows=generate_eval(current,tok,test)
row=round_metrics(r,initial_eval,eval_rows)
row.update({'generation':generation,'judging':judging,'training':training,'labelled_pairs':len(labelled),
'eval_generated_tokens':sum(len(x['sample']['tokens']) for x in eval_rows)})
report['rounds'].append(row)
if r==ROUNDS: report['status']='completo'
write_json(output,report)
print('Ronda',r,'win-rate',row['win_rate'],'pares evaluados',row['win_rate_denominator'],flush=True)
if __name__=='__main__': main()npm run lab and open the connection link.If win rate rises with length, do not automatically conclude bias: also compare by length group, inspect similarly sized pairs and request explicit evaluator criteria. A judge preferring a longer response may be detecting useful information or superficial content. Swapping presentation order reduces possible position bias, but does not make an automatic judge human truth.
Exercises
import math
beta, gamma, chosen_mean, rejected_mean = 2., 1., -1.2, -1.6
margin = beta * (chosen_mean - rejected_mean) - gamma
print('Margen:', margin)
print('Pérdida:', math.log1p(math.exp(-margin)))Step 1 of 3. How does DPO loss softplus(−βh) change as h increases?
import numpy as np
def ipo_loss(h, tau):
pass
def simpo_loss(chosen_mean, rejected_mean, beta, gamma):
pass
def kto_loss(logratios, labels, beta, z0, lambda_d, lambda_u):
pass
Each objective determines what signal it transforms and what distributions it needs. The tabular limit, data provenance and paired evaluation distinguish mathematical properties from empirical results.