Module contents
Lesson 18 of 26Core 105 min

Human preferences and reward models

Study pairwise preferences, Bradley-Terry and Plackett-Luce, reward models, their evaluation, and the KL cost of best-of-N selection.

After this lesson you can

  • Derive Bradley-Terry from latent Gumbel utilities and write its log-likelihood.
  • Estimate Bradley-Terry scores by maximum likelihood and discuss identifiability and regularization.
  • Train a scalar-head reward model on a small LLM using the loss −log σ(r_w − r_l).
  • Evaluate a reward model using held-out pair accuracy, inter-annotator agreement as a reference and length correlation.
  • Implement best-of-N with a reward model and derive its KL relative to the base policy, log N − (N − 1)/N.

Before you start

Compare before scoring

Imagine two summaries of the same document. One preserves the main idea but omits a condition; the other includes the condition and adds a questionable claim. Choosing which you prefer with explicit guidelines can be easier than writing a perfect summary or assigning an absolute score comparable across documents. The comparison remains an observation by a human or evaluator, subject to disagreement and error.

Pairwise preference data contain an instruction, two responses and a choice, sometimes accompanied by a tie, scores or annotator identity. The criterion matters: helpfulness, accuracy, safety and concision can conflict. Changing the guidelines or annotator population changes the meaning of the label.

Stiennon and colleagues published 64,832 comparisons of TL;DR summaries. In their training corpus, annotators agreed with one another 72% of the time; in a subset with sufficient shared comparisons, aggregating three labels raised agreement with researchers from 72% to 77%. These numbers belong to that protocol, not a universal mathematical ceiling for a model or evidence that every disagreement is an error.

UltraFeedback is another kind of evidence: it collected 63,967 instructions and 255,864 responses, evaluated with GPT-4. Its labels are not direct human preferences. Record who produced the responses, who evaluated them, the template, criteria and splits. Split by instruction before forming pairs: otherwise responses to the same prompt can appear in both training and evaluation.

The collection procedure also determines what questions the model can answer. If you always compare long answers from one generator with short answers from another, the label can correlate with both length and quality. Randomize display order where possible, record changes in criteria and retain ties. An origin-blind evaluation and an audit sample can detect some biases, although they do not by themselves resolve differences between people.

When an instruction has several responses, you can form several pairs from a ranking. Those pairs share context and judgment. If you split them separately across partitions or calculate uncertainty assuming complete independence, evaluation can appear more precise than it is. The unit of splitting and resampling must match the question you want to generalize to.

Bradley-Terry from noisy utilities

In the Bradley-Terry model, each alternative ii has score rir_i, and the probability of choosing aa over bb is

P(a≻b)=eraera+erb=σ(ra−rb).P(a\succ b)=\frac{e^{r_a}}{e^{r_a}+e^{r_b}}=\sigma(r_a-r_b).

Only the difference appears: adding the same constant to all scores changes no probability. Move the utilities in the arena, generate comparisons and observe what happens if one group stops being compared with another.

InteractiveBradley-Terry arena

The probability that i beats j is σ(rᵢ − rⱼ). On the vertical axis, 5 corresponds to A and 1 to E; utilities are centered to sum to zero.

  • estimate and bootstrap percentiles
  • latent utility

Mean absolute error of centered utilities: 0.206. Bootstrap: 80 of 80 resamples with finite fit.

Up to 50 results per pair are simulated using the kit’s reproducible generator. Reducing the control preserves a prefix for each pair. The penalty is λ‖r‖²/2 and comparison loss is averaged. Intervals resample comparisons with replacement; if the graph is disconnected, the penalty fixes a convention between groups without adding information.

-1.2
-0.5
0.0
0.6
1.1
Allowed comparisons
20
5
10
Comparisons
200
Undirected graph
connected
Win graph
strongly connected
L2
0.005
Compare estimates, uncertainty and connectivity from simulated preferences.

One derivation uses latent utilities Ui=ri+εiU_i=r_i+\varepsilon_i with independent Gumbel noise of equal scale. For unit scale, the cumulative distribution of UiU_i is Fi(t)=exp⁡[−e−(t−ri)]F_i(t)=\exp[-e^{-(t-r_i)}]. Integrating the density of UaU_a against FbF_b gives

P(Ua>Ub)=∫−∞∞fa(t)Fb(t) dt=eraera+erb.P(U_a>U_b)=\int_{-\infty}^{\infty} f_a(t)F_b(t)\,dt =\frac{e^{r_a}}{e^{r_a}+e^{r_b}}.

With common scale β>0\beta>0, the sigmoid’s argument is (ra−rb)/β(r_a-r_b)/\beta. Independence and common scale are model assumptions, not automatic properties of a survey. Bradley-Terry does not explicitly represent ties either: they must be discarded carefully or modeled by an extension.

To check the integral, set z=e−(t−ra)z=e^{-(t-r_a)}. Reversing the limits, the density of UaU_a transforms the integral into ∫0∞e−zexp⁡[−erb−raz] dz\int_0^\infty e^{-z}\exp[-e^{r_b-r_a}z]\,dz. The exponential integral equals 1/(1+erb−ra)1/(1+e^{r_b-r_a}), the sigmoid of the difference. The substitution makes clear why the common origin of the scores disappears.

For independent observations of winners wjw_j and losers ℓj\ell_j, the negative log-likelihood loss is

L(r)=∑jsoftplus⁡(rℓj−rwj).\mathcal L(r)=\sum_j\operatorname{softplus}(r_{\ell_j}-r_{w_j}).

One can fix ∑iri=0\sum_i r_i=0 to select a representation or add a quadratic penalty. In a connected undirected graph, score differences are identified under the model, up to translation. But existence of a finite unregularized maximum likelihood estimate requires further conditions: for ordinary binary comparisons, the directed graph of wins must be strongly connected. If one group always beats another, differences can grow without bound even when the undirected graph is connected.

If the graph has disconnected components, no observation determines their relative offset. An L2 penalty and a centering convention can produce a unique numerical solution, but the relative position between components comes from that choice, not from nonexistent comparisons. Bootstrap intervals also depend on the design: if multiple pairs share a prompt, resample groups of prompts rather than pretending they are independent observations.

For a comparison a≻ba\succ b, the derivative of the loss with respect to the margin d=ra−rbd=r_a-r_b is σ(d)−1\sigma(d)-1. If the margin is already very positive, the gradient contribution becomes small; if the model confidently favors the loser, the correction is large. Softplus avoids directly computing the logarithm of a probability that may round to zero. In Newton’s method, curvature has a null direction associated with adding a constant; restricting the step to the zero-sum subspace or regularizing avoids inverting a singular matrix without justification.

Rankings and successive choice

The Plackett-Luce model generalizes choice to a ranking without ties. For an order π1,…,πK\pi_1,\ldots,\pi_K, choose the first item among all, then the next among those remaining, and so on:

P(π)=∏j=1Kerπj∑k=jKerπk.P(\pi)=\prod_{j=1}^{K} \frac{e^{r_{\pi_j}}}{\sum_{k=j}^{K}e^{r_{\pi_k}}}.

The final factor equals one. Under independent Gumbel utilities with common scale, this product describes the induced order. Its independence of irrelevant alternatives assumption can fail when two responses are near duplicates or when evaluation depends on the other options presented. A complete ranking is not equivalent to observing all its pairs independently: sharing the same judgment creates dependence.

A scalar head on a language model

A reward model learns a score rθ(x,y)r_\theta(x,y) for an instruction xx and a response yy. One implementation adds a scalar head to a language model and reads the state of the last real token of each sequence. If there is padding, the mask must locate that token; reading the last tensor index can score padding. The template and truncation are part of the input definition.

With a chosen response ywy_w and a rejected response yℓy_\ell, a pairwise loss is

Lθ=softplus⁡ ⁣(rθ(x,yℓ)−rθ(x,yw)).\mathcal L_\theta=\operatorname{softplus}\!\left( r_\theta(x,y_\ell)-r_\theta(x,y_w)\right).

This is logistic loss applied to a difference. In logistic regression, minimizing it is equivalent to maximizing Bernoulli likelihood under the model. It does not require interpreting rθr_\theta as a calibrated universal utility: adding a shared constant for a prompt preserves its preferences. Regularizing or centering scores can help numerically, but does not create an absolute scale identified by pairs.

A large positive margin favors the observed label; a calibrated probability additionally requires checking frequencies on held-out data. A model that always assigns the correct sign with extreme confidence can have good accuracy and poor log-loss if it gets a few cases wrong. Store per-response scores, pairs and their groups, not just the final mean.

In pairwise training each response is processed with its own context and attention mask. A comparison’s gradient pushes the two scores in opposite directions, but model weights are shared across many prompts and responses: improvement on one pair can change others. If using LoRA, check which parameters remain trainable and save the base revision alongside the head and adapters. The scalar head must also be restored when loading the checkpoint to avoid inadvertently replacing it with a new initialization.

InteractiveWhat a reward model sees

Preparing the preference evaluation.

Examine margins measured on held-out pairs and their relationship to length.

Evaluate what was learned

Reward model evaluation includes pairwise accuracy, log-loss, calibration and subset analysis. A negative margin signals disagreement with the available label; it does not prove the label wrong: there can be ambiguity, legitimate human disagreement or model error. A second automatic evaluator is another signal, not infallible access to independent truth.

Inter-annotator agreement is a reference for the same dataset and protocol. A model may agree with a majority more often than an individual annotator if aggregation reduces noise, and values are not comparable if populations, instructions or questions change. Estimate uncertainty, especially with few prompts, and inspect examples where model and evaluators disagree.

An idealized example shows why it is not a ceiling: for a question, suppose each annotator chooses A with probability 0,80{,}8 and B with probability 0,20{,}2 independently of the others. Two annotators agree with probability 0,82+0,22=0,680{,}8^2+0{,}2^2=0{,}68, whereas a predictor that always chooses A agrees with an annotator with probability 0,80{,}8. The following cell computes this. It is a hypothetical model of variability, not an explanation of Stiennon’s numbers or a guarantee about real annotators.

[ ]PythonBrowser
p = 0.8
print("Acuerdo de dos anotadores hipotéticos:", p*p + (1-p)*(1-p))
print("Acuerdo del predictor mayoritario:", p)

Length can act as a spurious signal. Compute the length difference between chosen and rejected responses and compare margins within length intervals, as well as reporting a correlation. Correlation alone does not establish causality: a longer answer can contain useful information or filler. Singhal and colleagues studied length and reward correlations in several RLHF settings; their findings motivate checking the phenomenon on your own distribution, not assuming every preference for longer responses is wrong.

For a calibration curve, group similar predicted probabilities and compare average confidence with observed label frequency. Also show how many pairs are in each group: a bar based on very few examples is unstable. Pairwise accuracy, calibration and length correlation answer different questions. Furthermore, filtering by length changes the population analyzed; retain both overall and stratified results.

RewardBench brings together reward-model evaluations with different types of pairs. A single benchmark does not cover every failure or guarantee that responses generated by an optimized policy follow the same distribution as training pairs. Also evaluate responses from the policy that will use the model and retain a human audit for questions where one is needed.

Best-of-N and the cost of selection

In best-of-N, for a fixed prompt generate NN independent responses from a base policy π0\pi_0 and choose the one with the highest reward-model score. You do not update policy weights, but you change its effective distribution and pay to generate and evaluate NN candidates. Higher proxy reward does not guarantee better quality under another criterion.

InteractiveBest-of-N: reward versus KL

Preparing the reproducible simulation.

Explore an explicit proxy and reference model and observe their relationship to candidate count.

Now suppose score R(Y)R(Y) of Y∼π0Y\sim\pi_0 has a continuous distribution, so ties have no positive probability. Let FF be its cumulative distribution function and πN\pi_N the distribution of the selected response. Then

dπNdπ0(y)=N F(R(y))N−1.\frac{d\pi_N}{d\pi_0}(y)=N\,F(R(y))^{N-1}.

Indeed, any of the NN positions can produce yy and the others must have lower scores. Under the selected policy, U=F(R(Y))U=F(R(Y)) has density NuN−1Nu^{N-1} on [0,1][0,1]. Integrating the logarithm of the density ratio gives

DKL(πN∥π0)=log⁡N+(N−1)∫01NuN−1log⁡u du=log⁡N−N−1N.D_{\mathrm{KL}}(\pi_N\Vert\pi_0) =\log N+(N-1)\int_0^1 Nu^{N-1}\log u\,du =\log N-\frac{N-1}{N}.

Equality requires the stated assumptions. Language-model responses are discrete and can tie in score. In that case, with the selection procedure studied by Beirami and colleagues, the same expression is an upper bound, not the exact KL in general. If all responses have the same reward and the first candidate is chosen, the resulting policy is π0\pi_0 and KL is zero for any NN.

To see a discrete KL without approximations, consider two equally likely responses with different rewards and N=2N=2. The lower-reward one is selected only if both samples are that response, with probability 1/41/4; the other is selected with probability 3/43/4. The exact KL is 14log⁡(1/2)+34log⁡(3/2)\tfrac14\log(1/2)+\tfrac34\log(3/2), less than the continuous expression log⁡2−1/2\log 2-1/2. The cell checks both quantities. Pairing and the tie-breaking rule must be declared when calculating a discrete distribution.

[ ]PythonBrowser
import math
kl_binaria = .25 * math.log(.25/.5) + .75 * math.log(.75/.5)
kl_continua = math.log(2) - .5
print("KL discreta binaria:", kl_binaria)
print("Cota continua para N=2:", kl_continua)

The figure’s curve is an explicit model for studying what happens when proxy and reference differ. It is not an experiment on all tasks and does not prove increasing NN always reduces quality. In the lab retain candidates, seed, temperature, reward-model scores and independent evaluator scores; compare by prompt and avoid using that evaluator for selection and then presenting it as an independent measure.

The average maximum proxy score cannot decrease when adding a candidate to the same nested set. The selected candidate’s reference score can rise, plateau or fall: selection uses the proxy, not the reference. The interactive model declares how it generates both signals and is a hypothesis you can check with its simulation. If the proxy has different noise, the curve may change.

The derived KL is a divergence between distributions of complete responses for a fixed prompt, not a distance between two scores or two individual samples. For multiple prompts you can average conditional KLs under a declared prompt distribution. The continuous formula also excludes computational cost and does not prove the selected response correct: it measures how much the distribution changes under its assumptions.

An ensemble of reward models can reveal disagreement or reduce some variance, but similar models can share biases. Step verifiers and process rewards evaluate intermediate signals instead of only the final outcome; their errors and usefulness depend on which steps and criteria are observed. We revisit this distinction when studying reasoning and tools.

Lab: Bradley-Terry and rankings

This example generates comparisons with fixed utilities and a seed; the simulated responses are not human preferences. The objective averages logistic loss per comparison and adds an L2 penalty. All scores are constrained to sum to zero. Gradient and Newton methods are compared, pairwise comparisons are resampled for intervals, and Plackett-Luce is checked by enumerating all rankings of three items.

A connected undirected comparison network identifies differences, but does not guarantee a finite maximum of the observed likelihood: directed wins must be strongly connected. L2 makes the solution unique even with disconnected components, though comparisons still do not identify their relative offsets. The bootstrap is conditional on this pair design; for data with multiple pairs per prompt, resample whole prompts.

[ ]Bradley-Terry and Plackett-Luce from scratchBrowser
import itertools
import numpy as np

SEED = 1810
TRUE = np.array([-1.2, -.5, 0., .6, 1.1])
assert abs(TRUE.sum()) < 1e-12

def simulate(scores, per_pair, seed):
    random = np.random.default_rng(seed)
    comparisons = []
    for i in range(len(scores)):
        for j in range(i + 1, len(scores)):
            p = 1 / (1 + np.exp(scores[j] - scores[i]))
            for value in random.random(per_pair):
                comparisons.append((i, j) if value < p else (j, i))
    return np.asarray(comparisons, dtype=int)

def connectivity(pairs, k):
    directed = np.eye(k, dtype=bool)
    for winner, loser in pairs:
        directed[winner, loser] = True
    undirected = directed | directed.T
    for t in range(k):
        directed |= directed[:, t, None] & directed[None, t, :]
        undirected |= undirected[:, t, None] & undirected[None, t, :]
    return bool(undirected.all()), bool(directed.all())

def basis(k):
    # r = B u implica suma(r)=0. No necesita BLAS ni guardar una matriz grande.
    return np.vstack((np.eye(k - 1), -np.ones((1, k - 1))))

def loss_grad_hessian(u, pairs, k, ridge):
    B = basis(k); r = B @ u
    x = B[pairs[:, 0]] - B[pairs[:, 1]]
    delta = x @ u
    p = 1 / (1 + np.exp(-np.clip(delta, -50, 50)))
    loss = float(np.logaddexp(0, -delta).mean() + ridge * (r @ r) / 2)
    grad = (x.T @ (p - 1)) / len(pairs) + ridge * (B.T @ r)
    hess = (x.T @ (x * (p * (1 - p))[:, None])) / len(pairs) + ridge * (B.T @ B)
    return loss, grad, hess

def fit(pairs, k, ridge=0., method='newton', max_iter=3000):
    if len(pairs) == 0 or ridge < 0: raise ValueError('Se necesitan comparaciones y L2 no negativo')
    connected, strong = connectivity(pairs, k)
    if ridge == 0 and not strong:
        raise ValueError('El MLE sin regularizar no es finito y único con este grafo de victorias')
    if method not in ('newton', 'gradient'): raise ValueError('Método desconocido')
    u = np.zeros(k - 1)
    for iteration in range(max_iter):
        loss, grad, hess = loss_grad_hessian(u, pairs, k, ridge)
        if np.max(np.abs(grad)) < 1e-8: break
        step = np.linalg.solve(hess, grad) if method == 'newton' else grad
        rate = 1.
        for _ in range(30):
            candidate = u - rate * step
            if loss_grad_hessian(candidate, pairs, k, ridge)[0] <= loss - 1e-4 * rate * (grad @ step): break
            rate *= .5
        else: raise RuntimeError('No se encontró un paso descendente')
        u = candidate
    else: raise RuntimeError('No convergió con el presupuesto indicado')
    return {'scores': basis(k) @ u, 'loss': loss, 'iterations': iteration,
            'undirected_connected': connected, 'strongly_connected': strong}

def log_plackett_luce(scores, ranking):
    scores = np.asarray(scores, dtype=float)
    if sorted(ranking) != list(range(len(scores))): raise ValueError('El ranking debe ser una permutación')
    result = 0.
    for t, item in enumerate(ranking[:-1]):
        remaining = scores[ranking[t:]]
        maximum = remaining.max()
        result += scores[item] - (maximum + np.log(np.exp(remaining - maximum).sum()))
    return float(result)

pairs = simulate(TRUE, per_pair=20, seed=SEED)
ridge = .001
newton = fit(pairs, 5, ridge, 'newton')
gradient = fit(pairs, 5, ridge, 'gradient')
assert np.max(np.abs(newton['scores'] - gradient['scores'])) < 2e-6
assert abs(newton['scores'].sum()) < 1e-12
# Diferencias finitas del gradiente en coordenadas independientes.
point = np.array([.2, -.3, .1, .15]); eps = 1e-6
_, analytic, hessian = loss_grad_hessian(point, pairs, 5, ridge)
finite = np.array([(loss_grad_hessian(point + eps*np.eye(4)[i], pairs, 5, ridge)[0]
                    - loss_grad_hessian(point - eps*np.eye(4)[i], pairs, 5, ridge)[0])/(2*eps) for i in range(4)])
assert np.max(abs(analytic - finite)) < 1e-8
finite_hessian = np.column_stack([(loss_grad_hessian(point + eps*np.eye(4)[i], pairs, 5, ridge)[1]
                                 - loss_grad_hessian(point - eps*np.eye(4)[i], pairs, 5, ridge)[1])/(2*eps) for i in range(4)])
assert np.max(abs(hessian - finite_hessian)) < 1e-8

random = np.random.default_rng(SEED + 1); draws = []
for _ in range(120):
    sample = pairs[random.integers(0, len(pairs), len(pairs))]
    draws.append(fit(sample, 5, ridge)['scores'])
intervals = np.quantile(np.asarray(draws), [.025, .975], axis=0)
scores = np.array([-.4, .1, .8]); rankings = list(itertools.permutations(range(3)))
probabilities = np.array([np.exp(log_plackett_luce(scores, list(p))) for p in rankings])
assert abs(probabilities.sum() - 1) < 1e-12
assert abs(log_plackett_luce(scores, [2, 0, 1]) - log_plackett_luce(scores + 8, [2, 0, 1])) < 1e-12

disconnected = pairs[((pairs[:, 0] < 2) & (pairs[:, 1] < 2)) | ((pairs[:, 0] >= 2) & (pairs[:, 1] >= 2))]
assert connectivity(disconnected, 5)[0] is False
shift = np.array([1., 1., -2/3, -2/3])
assert abs(loss_grad_hessian(point, disconnected, 5, 0)[0] - loss_grad_hessian(point + shift, disconnected, 5, 0)[0]) < 1e-12
assert np.all(np.isfinite(fit(disconnected, 5, ridge)['scores']))
try: fit(disconnected, 5, 0.)
except ValueError: pass
else: raise AssertionError('El MLE desconectado no es identificable')
separated = np.array([(0, 1), (1, 2), (2, 3), (3, 4)])
assert connectivity(separated, 5) == (True, False)
try: fit(separated, 5, 0.)
except ValueError: pass
else: raise AssertionError('La separación no admite MLE finito')
print('Comparaciones:', len(pairs), 'grafo no dirigido y dirigido:', connectivity(pairs, 5))
print('Utilidades reales:', TRUE, 'Newton:', newton['scores'], 'gradiente:', gradient['scores'])
print('Error máximo entre métodos:', float(np.max(abs(newton['scores'] - gradient['scores']))))
print('Error máximo de gradiente por diferencias finitas:', float(np.max(abs(analytic - finite))))
print('Error máximo del Hessiano por diferencias finitas:', float(np.max(abs(hessian - finite_hessian))))
print('Intervalos bootstrap 2,5 % y 97,5 %, 120 remuestras:', intervals)
print('Plackett-Luce, suma de las 6 permutaciones:', float(probabilities.sum()))
print('Grafo desconectado y separación dirigida detectados; L2 fija una convención sin añadir comparaciones.')

Lab: train a reward model

We train a reward model with binarized UltraFeedback, revision 3949bf5f8c17c394422ccfab0c31ea9c20bdeb85. Its labels come from GPT-4 scores, not direct human preferences; we exclude tied or inconsistent scores and overly long pairs. We use test_prefs as a holdout, remove every test prompt from train_prefs and assign validation or training by prompt hash. The split removes exact normalized matches, not paraphrases. The report shows pairwise accuracy and a mean giving each prompt equal weight: several pairs from the same prompt are not independent observations.

The bias-free linear head reads the last real token of the full user-and-assistant template, without padding. Qwen2.5-0.5B-Instruct base weights stay frozen; we train the head and LoRA with softplus(r_rechazada - r_elegida). The difference between rewards matters, but a common offset does not change preference. The lab also reports Brier and calibration bins with both orientations of each pair, and correlates response-token length difference with margin. These results do not prove length causes preference or establish a human-agreement ceiling.

As a control independent of the label, Qwen2.5-3B-Instruct is used as an open judge: it compares the same pairs in both orders and averages differences in logits of tokens A and B. This model was not trained as a reward model in this lab, its vote is not ground truth, and it may suffer position or model-family biases. The program first saves the reward-model report with the judge pending; if the second load does not fit, that report preserves the actual measurements and notes the absence. ORYON_REWARD_SKIP_JUDGE=1 explicitly skips the second load. Do not interpret disagreement as automatic evidence of a label error.

Install torch, transformers, peft, datasets, huggingface_hub and safetensors. Normal mode uses 512 training pairs, 64 validation and 128 test pairs, with 256 updates. ORYON_QUICK=1 uses 8, 4 and 8 pairs and only two updates to check the flow, without promising any trend. Set ORYON_REWARD_DIR to choose where to save the adapter, head, metadata, test prompts and report. Weights load sequentially and their hashes are recorded. For offline use, ORYON_OFFLINE=1 requires cached snapshots and ORYON_REWARD_JSONL with rows labeled by split as train_prefs or test_prefs; the file’s provenance is unverified and it is identified by its SHA-256. The next cell uses the checkpoint and held-out prompts without retraining the reward model.

[ ]Reward model with LoRA and pairwise comparisonLocal GPU
"""Reward model por pares con cabeza escalar, LoRA y evaluación agrupada."""
import gc
import hashlib
import json
import math
import os
import random
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 LoraConfig, get_peft_model
from safetensors.torch import save_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'
OUT = Path(os.getenv('ORYON_REWARD_DIR', './oryon-reward'))
DATA_LOCAL = os.getenv('ORYON_REWARD_JSONL', '')
MODEL = 'Qwen/Qwen2.5-0.5B-Instruct'
MODEL_REV = '7ae557604adf67be50417f59c2c2f167def9a775'
JUDGE = 'Qwen/Qwen2.5-3B-Instruct'
JUDGE_REV = 'aa8e72537993ba99e69dfaafa59ed015b17504d1'
DATA = 'HuggingFaceH4/ultrafeedback_binarized'
DATA_REV = '3949bf5f8c17c394422ccfab0c31ea9c20bdeb85'
SEED = 1818
MAX_CONTEXT = 384
TRAIN_COUNT, VAL_COUNT, TEST_COUNT = (8, 4, 8) if QUICK else (512, 64, 128)
STEPS = 2 if QUICK else 256
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 open(path, 'rb') as f:
        for part in iter(lambda: f.read(1024 * 1024), b''): h.update(part)
    return h.hexdigest()

def snapshot_hashes(repo, revision):
    snapshot = Path(snapshot_download(repo, revision=revision, local_files_only=OFFLINE,
                                     allow_patterns=['*.safetensors','config.json','tokenizer.json']))
    weights = {path.name: file_hash(path) for path in sorted(snapshot.glob('*.safetensors'))}
    if not weights: raise ValueError('No se encontraron pesos safetensors para calcular sus huellas')
    return weights

def source(split):
    if DATA_LOCAL:
        def read():
            with open(DATA_LOCAL, encoding='utf-8') as f:
                for line in f:
                    row = json.loads(line)
                    if row.get('split') == split: yield row
        return read()
    if OFFLINE: raise ValueError('Fija ORYON_REWARD_JSONL para usar datos sin red')
    return iter(load_dataset(DATA, split=split, revision=DATA_REV, streaming=True))

def parse(row):
    chosen, rejected = row.get('chosen'), row.get('rejected')
    if not isinstance(chosen, list) or not isinstance(rejected, list) or len(chosen) != 2 or len(rejected) != 2:
        raise ValueError('Se requieren dos turnos por respuesta')
    if not all(isinstance(m, dict) for m in chosen + rejected): raise ValueError('Turno no válido')
    if [m.get('role') for m in chosen] != ['user','assistant'] or [m.get('role') for m in rejected] != ['user','assistant']:
        raise ValueError('Roles inesperados')
    q, w, l = chosen[0].get('content'), chosen[1].get('content'), rejected[1].get('content')
    if not all(isinstance(x, str) and x.strip() for x in (q,w,l)) or q != rejected[0].get('content'):
        raise ValueError('El prompt debe coincidir en ambas respuestas')
    if len(q) > 400 or len(w) > 600 or len(l) > 600: raise ValueError('Longitud filtrada')
    sw, sl = row.get('score_chosen'), row.get('score_rejected')
    if not isinstance(sw, (int,float)) or not isinstance(sl, (int,float)) or not sw > sl:
        raise ValueError('Empate, puntuación ausente o etiqueta incoherente')
    return {'prompt': q, 'chosen': w, 'rejected': l, 'prompt_hash': sha(normal(q)),
            'chosen_hash': sha(w), 'rejected_hash': sha(l),
            'source_chosen_score': float(sw), 'source_rejected_score': float(sl)}

def token_ids(tokenizer, prompt, answer):
    if any(t and t in prompt + answer for t in tokenizer.all_special_tokens):
        raise ValueError('El contenido incluye una grafía de token especial')
    ids = tokenizer.apply_chat_template([{'role':'user','content':prompt}, {'role':'assistant','content':answer}],
                                        tokenize=True, add_generation_prompt=False)
    if isinstance(ids, Mapping): ids = ids['input_ids']
    if not ids or len(ids) > MAX_CONTEXT: raise ValueError('La pareja supera el contexto')
    return ids

def collect(tokenizer):
    test, seen_pairs, rejected = [], set(), defaultdict(int)
    for row in source('test_prefs'):
        try:
            item = parse(row)
            token_ids(tokenizer, item['prompt'], item['chosen']); token_ids(tokenizer, item['prompt'], item['rejected'])
        except ValueError as exc:
            rejected[str(exc)] += 1; continue
        pair = (item['prompt_hash'], item['chosen_hash'], item['rejected_hash'])
        if pair in seen_pairs: continue
        seen_pairs.add(pair); test.append(item)
        if len(test) == TEST_COUNT: break
    if len(test) != TEST_COUNT: raise ValueError('No hay suficientes pares test válidos')
    blocked = {p['prompt_hash'] for p in test}
    train, val, split_by_prompt = [], [], {}
    for row in source('train_prefs'):
        try:
            item = parse(row)
            token_ids(tokenizer, item['prompt'], item['chosen']); token_ids(tokenizer, item['prompt'], item['rejected'])
        except ValueError as exc:
            rejected[str(exc)] += 1; continue
        key = item['prompt_hash']
        if key in blocked: continue
        pair = (key, item['chosen_hash'], item['rejected_hash'])
        if pair in seen_pairs: continue
        seen_pairs.add(pair)
        group = 'val' if int(key[:8],16) % 10 == 0 else 'train'
        split_by_prompt[key] = group
        if group == 'val' and len(val) < VAL_COUNT: val.append(item)
        if group == 'train' and len(train) < TRAIN_COUNT: train.append(item)
        if len(train) == TRAIN_COUNT and len(val) == VAL_COUNT: break
    if len(train) != TRAIN_COUNT or len(val) != VAL_COUNT: raise ValueError('Faltan pares train o validación')
    assert not {p['prompt_hash'] for p in train} & {p['prompt_hash'] for p in val}
    assert not ({p['prompt_hash'] for p in train+val} & blocked)
    return train, val, test, dict(rejected)

def score(backbone, head, ids):
    inputs = torch.tensor([ids], dtype=torch.long, device='cuda')
    # Un ejemplo por llamada: no hay padding; el último token pertenece a la plantilla real.
    hidden = backbone(input_ids=inputs, attention_mask=torch.ones_like(inputs),
                      use_cache=False, return_dict=True).last_hidden_state[0, -1]
    return head(hidden.float()).squeeze(-1)

def pair_scores(backbone, head, tokenizer, pair):
    a = token_ids(tokenizer, pair['prompt'], pair['chosen'])
    b = token_ids(tokenizer, pair['prompt'], pair['rejected'])
    return (score(backbone, head, a), score(backbone, head, b),
            len(tokenizer.encode(pair['chosen'], add_special_tokens=False)),
            len(tokenizer.encode(pair['rejected'], add_special_tokens=False)))

def sigmoid(x):
    return 1 / (1 + math.exp(-max(-60., min(60., x))))

def metrics(rows):
    if not rows: raise ValueError('No hay pares para evaluar')
    groups = defaultdict(list)
    for x in rows: groups[x['prompt_hash']].append(1. if x['margin'] > 0 else .5 if x['margin'] == 0 else 0.)
    correct = [1. if x['margin'] > 0 else .5 if x['margin'] == 0 else 0. for x in rows]
    probs = [sigmoid(x['margin']) for x in rows]
    bins = []
    # Ambas orientaciones de cada par producen (p,1) y (1-p,0).
    for k in range(10):
        items = [(p,1) for p in probs] + [(1-p,0) for p in probs]
        subset = [(p,y) for p,y in items if min(int(p * 10), 9) == k]
        if subset:
            bins.append({'bin': k, 'n': len(subset), 'confidence': sum(p for p,_ in subset)/len(subset),
                         'frequency': sum(y for _,y in subset)/len(subset)})
    x = np.array([r['length_difference'] for r in rows], dtype=float)
    y = np.array([r['margin'] for r in rows], dtype=float)
    correlation = float(np.corrcoef(x,y)[0,1]) if len(rows) > 1 and x.std() > 0 and y.std() > 0 else None
    return {'pairs': len(rows), 'prompts': len(groups), 'pair_accuracy': sum(correct)/len(rows),
            'prompt_balanced_accuracy': sum(sum(v)/len(v) for v in groups.values())/len(groups),
            'pair_brier': sum((1-p)**2 for p in probs)/len(probs), 'bins_symmetric': bins,
            'ece_10_symmetric': sum(b['n'] * abs(b['confidence'] - b['frequency']) for b in bins)/(2*len(rows)),
            'pearson_margin_length_difference': correlation}

def evaluate(backbone, head, tokenizer, pairs):
    backbone.eval(); head.eval(); output = []
    with torch.no_grad():
        for p in pairs:
            rw, rl, nw, nl = pair_scores(backbone, head, tokenizer, p)
            output.append({**p, 'reward_chosen': float(rw), 'reward_rejected': float(rl),
                           'margin': float(rw-rl), 'length_chosen': nw, 'length_rejected': nl,
                           'length_difference': nw-nl})
    return output, metrics(output)

def judge_input(tokenizer, pair, swapped):
    first, second = (pair['rejected'], pair['chosen']) if swapped else (pair['chosen'], pair['rejected'])
    prompt = ('Choose the better answer to the user request. Reply with A or B only.\n'
              'User request: ' + pair['prompt'] + '\nAnswer A:\n' + first + '\nAnswer B:\n' + second)
    ids = tokenizer.apply_chat_template([{'role':'user','content':prompt}], tokenize=True, add_generation_prompt=True)
    if isinstance(ids, Mapping): ids = ids['input_ids']
    if len(ids) > 1024: raise ValueError('Par demasiado largo para el juez')
    return ids

def judge(rows):
    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): raise ValueError('A y B deben ser tokens individuales')
    model = AutoModelForCausalLM.from_pretrained(JUDGE, revision=JUDGE_REV, local_files_only=OFFLINE,
                                                  dtype=torch.bfloat16, device_map={'':0}).eval()
    hashes = snapshot_hashes(JUDGE, JUDGE_REV)
    with torch.no_grad():
        for row in rows:
            scores = []
            try:
                for swap in (False, True):
                    ids = judge_input(tok, row, swap)
                    logits = model(input_ids=torch.tensor([ids], device='cuda'), use_cache=False).logits[0,-1]
                    scores.append(float(logits[labels[0][0]] - logits[labels[1][0]]))
                row['judge'] = {'ab_logit_difference': scores[0], 'ba_logit_difference': scores[1],
                                'chosen_vs_rejected': (scores[0]-scores[1])/2}
            except ValueError as exc:
                row['judge'] = {'unavailable': str(exc)}
    del model; gc.collect(); torch.cuda.empty_cache()
    return hashes

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)
    tokenizer = AutoTokenizer.from_pretrained(MODEL, revision=MODEL_REV, local_files_only=OFFLINE)
    train, val, test, rejected = collect(tokenizer)
    source_id = 'JSONL local, origen por verificar' if DATA_LOCAL else DATA
    source_revision = None if DATA_LOCAL else DATA_REV
    test_prompts = {p['prompt_hash']: p['prompt'] for p in test}
    with (OUT / 'test-prompts.jsonl').open('w', encoding='utf-8') as f:
        for key, prompt in test_prompts.items():
            f.write(json.dumps({'prompt_id':key, 'prompt':prompt, 'source':source_id,
                                'revision':source_revision, 'split':'test_prefs'}, ensure_ascii=False) + '\n')
    backbone = AutoModel.from_pretrained(MODEL, revision=MODEL_REV, local_files_only=OFFLINE,
                                        dtype=torch.float32, attn_implementation='sdpa').to('cuda')
    base_hashes = snapshot_hashes(MODEL, MODEL_REV)
    backbone.config.use_cache = False
    backbone.gradient_checkpointing_enable(gradient_checkpointing_kwargs={'use_reentrant':False})
    config = LoraConfig(r=8, lora_alpha=16, lora_dropout=.05, bias='none', task_type='FEATURE_EXTRACTION',
                        target_modules=['q_proj','k_proj','v_proj','o_proj'])
    backbone = get_peft_model(backbone, config)
    head = torch.nn.Linear(backbone.config.hidden_size, 1, bias=False, device='cuda', dtype=torch.float32)
    params = [p for p in backbone.parameters() if p.requires_grad] + list(head.parameters())
    opt = torch.optim.AdamW(params, lr=1e-4)
    history = []
    for step in range(STEPS):
        backbone.train(); head.train(); opt.zero_grad(set_to_none=True)
        pair = train[step % len(train)]
        rw, rl, _, _ = pair_scores(backbone, head, tokenizer, pair)
        loss = F.softplus(rl-rw); loss.backward()
        torch.nn.utils.clip_grad_norm_(params, 1.)
        opt.step(); history.append(float(loss.detach()))
    validation, validation_metrics = evaluate(backbone, head, tokenizer, val)
    results, test_metrics = evaluate(backbone, head, tokenizer, test)
    backbone.save_pretrained(OUT / 'adapter', safe_serialization=True)
    tokenizer.save_pretrained(OUT / 'adapter')
    save_file({'weight': head.weight.detach().cpu().contiguous()}, str(OUT / 'reward-head.safetensors'))
    metadata = {'model':MODEL, 'revision':MODEL_REV, 'weights_sha256':base_hashes, 'hidden_size':backbone.config.hidden_size,
                'head':'linear sin sesgo', 'dtype':'float32', 'pooling':'último token real, sin padding',
                'max_context':MAX_CONTEXT, 'template':'apply_chat_template user + assistant',
                'adapter':'adapter', 'head_file':'reward-head.safetensors',
                'adapter_sha256':file_hash(OUT / 'adapter' / 'adapter_model.safetensors'),
                'head_sha256':file_hash(OUT / 'reward-head.safetensors')}
    (OUT / 'reward-meta.json').write_text(json.dumps(metadata, ensure_ascii=False, indent=2), encoding='utf-8')
    del opt, head, backbone; gc.collect(); torch.cuda.empty_cache()
    data_source = {'id': source_id, 'revision': source_revision,
                   'annotation':'no verificada para la fuente local' if DATA_LOCAL else 'GPT-4, preferencias binarizadas',
                   'local_sha256': file_hash(DATA_LOCAL) if DATA_LOCAL else None}
    report = {'model':metadata, 'data':data_source, 'seed':SEED, 'quick':QUICK, 'steps':STEPS,
              'split_policy':'test_prefs; train_prefs se divide por hash del prompt y excluye prompts test.',
              'train_prompt_hashes':[r['prompt_hash'] for r in train],
              'validation_prompt_hashes':[r['prompt_hash'] for r in val],
              'test_prompt_hashes':[r['prompt_hash'] for r in test],
              'rejected':rejected, 'training_loss':history, 'validation_metrics':validation_metrics,
              'test_metrics':test_metrics, 'test':results,
              'judge':{'id':JUDGE, 'revision':JUDGE_REV, 'status':'pendiente',
                       'description':'Dos órdenes, media de diferencias de logits A/B. No es un árbitro infalible.'},
              'limitations':'Etiquetas GPT-4, sin techo de acuerdo humano; pocos pares, sin garantía de calibración ni causalidad por longitud.'}
    report_path = OUT / 'reward-report.json'
    report_path.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')
    if os.getenv('ORYON_REWARD_SKIP_JUDGE') != '1':
        if not torch.cuda.is_bf16_supported(): raise RuntimeError('El juez requiere CUDA con bfloat16')
        judge_hashes = judge(results)
        available = [r for r in results if 'chosen_vs_rejected' in r.get('judge', {})]
        decisive = [r for r in available if r['margin'] != 0 and r['judge']['chosen_vs_rejected'] != 0]
        agreement = sum((r['margin'] > 0) == (r['judge']['chosen_vs_rejected'] > 0) for r in decisive)
        report['judge'].update({'status':'evaluado', 'weights_sha256':judge_hashes,
                                'pairs_available':len(available), 'pairs_decisive':len(decisive),
                                'agreement':agreement/len(decisive) if decisive else None})
        report_path.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')
    else:
        report['judge']['status'] = 'omitido'
        report_path.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')
    print('Validación:', validation_metrics, 'test:', test_metrics, 'juez:', report['judge'], flush=True)

if __name__ == '__main__': main()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Lab: best-of-N with models

[ ]Best-of-N with an independent judgeLocal GPU
"""Best-of-N con política SFT, reward model y juez independiente.

Ejecuta primero los laboratorios de m20-l15 y m20-l18 y conserva sus salidas.
La prueba QUICK reduce prompts y candidatos, no constituye una evaluación real.
"""
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 peft import PeftModel
from safetensors.torch import load_file
from transformers import AutoModel, AutoModelForCausalLM, AutoTokenizer

QUICK = os.getenv('ORYON_QUICK') == '1'
OFFLINE = os.getenv('ORYON_OFFLINE') == '1'
SFT = Path(os.getenv('ORYON_SFT_DIR', './oryon-sft'))
REWARD = Path(os.getenv('ORYON_REWARD_DIR', './oryon-reward'))
OUT = Path(os.getenv('ORYON_BON_DIR', './oryon-best-of-n'))
JUDGE = 'Qwen/Qwen2.5-3B-Instruct'
JUDGE_REV = 'aa8e72537993ba99e69dfaafa59ed015b17504d1'
SEED = 181819
NS = [1, 2, 4] if QUICK else [1, 2, 4, 8, 16]
N_PROMPTS = 2 if QUICK else 16
NEW_TOKENS = 24 if QUICK else 80
torch.set_num_threads(1)

def file_hash(path):
    h = hashlib.sha256()
    with path.open('rb') as f:
        for block in iter(lambda: f.read(1024 * 1024), b''): h.update(block)
    return h.hexdigest()

def prompt_hash(text):
    return hashlib.sha256(' '.join(text.split()).casefold().encode('utf-8')).hexdigest()

def kl_bound(n):
    if n < 1: raise ValueError('N debe ser positivo')
    return math.log(n) - (n - 1) / n

def plain(tok, text):
    if any(t and t in text for t in tok.all_special_tokens):
        raise ValueError('Texto ordinario contiene grafías de tokens especiales')
    ids = tok.encode(text, add_special_tokens=False)
    if set(ids) & set(tok.all_special_ids): raise ValueError('Token de control en texto ordinario')
    if tok.decode(ids, skip_special_tokens=False, clean_up_tokenization_spaces=False) != text:
        raise ValueError('El texto no permite ida y vuelta exacta')
    return ids

def sft_prompt(tok, prompt):
    start = tok.convert_tokens_to_ids('<|im_start|>')
    end = tok.convert_tokens_to_ids('<|im_end|>')
    if (start, end) != (1, 2): raise ValueError('La plantilla exige los ID de SmolLM2 de m20-l15')
    return [start] + plain(tok, 'user\n') + plain(tok, prompt) + [end] + plain(tok, '\n') + [start] + plain(tok, 'assistant\n')

def load_prompts():
    report_path = REWARD / 'reward-report.json'
    report = json.loads(report_path.read_text(encoding='utf-8'))
    permitted = set(report['test_prompt_hashes'])
    forbidden = set(report['train_prompt_hashes']) | set(report['validation_prompt_hashes'])
    if permitted & forbidden: raise ValueError('Solapamiento de prompts del reward model')
    prompts, seen = [], set()
    path = REWARD / 'test-prompts.jsonl'
    with path.open(encoding='utf-8') as f:
        for line in f:
            row = json.loads(line)
            key = prompt_hash(row['prompt'])
            if row['prompt_id'] != key or key not in permitted or row['split'] != 'test_prefs':
                raise ValueError('Prompt no corresponde al test declarado en el informe')
            if key not in seen:
                prompts.append(row); seen.add(key)
                if len(prompts) == N_PROMPTS: break
    if len(prompts) != N_PROMPTS: raise ValueError('No hay suficientes prompts test únicos')
    return prompts, report, file_hash(path), file_hash(report_path)

def generate(prompts):
    model_dir = SFT / 'final'
    sft_report_path = SFT / 'sft-report.json'
    sft_report = json.loads(sft_report_path.read_text(encoding='utf-8'))
    if not sft_report.get('checkpoint_saved'): raise ValueError('m20-l15 no guardó su checkpoint')
    weights = sorted(model_dir.glob('*.safetensors'))
    if not weights: raise FileNotFoundError('Faltan los pesos del checkpoint SFT')
    hashes = {p.name: file_hash(p) for p in weights}
    tok = AutoTokenizer.from_pretrained(model_dir, local_files_only=True)
    model = AutoModelForCausalLM.from_pretrained(model_dir, dtype=torch.float32, local_files_only=True).to('cuda').eval()
    samples = []
    with torch.inference_mode():
        for row in prompts:
            prefix = sft_prompt(tok, row['prompt'])
            if len(prefix) + NEW_TOKENS > model.config.max_position_embeddings:
                raise ValueError('Prompt SFT no cabe sin truncamiento')
            x = torch.tensor([prefix], device='cuda')
            candidates = []
            for _ in range(max(NS)):
                y = model.generate(x, attention_mask=torch.ones_like(x), do_sample=True,
                                   temperature=.8, top_p=.9, max_new_tokens=NEW_TOKENS,
                                   eos_token_id=[0, 2], pad_token_id=0)[0, len(prefix):]
                ids = y.tolist()
                text = tok.decode(ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)
                candidates.append({'text':text, 'token_ids':ids})
            samples.append({'prompt_id':row['prompt_id'], 'prompt':row['prompt'], 'candidates':candidates})
    del model, tok; gc.collect(); torch.cuda.empty_cache()
    return samples, hashes, file_hash(sft_report_path), sft_report

def reward_scores(rows, meta):
    tok = AutoTokenizer.from_pretrained(REWARD / '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 / 'adapter').eval()
    weight = load_file(str(REWARD / meta['head_file']), device='cpu')['weight'].to('cuda').float()
    if tuple(weight.shape) != (1, meta['hidden_size']): raise ValueError('Forma de cabeza inesperada')
    with torch.inference_mode():
        for row in rows:
            for c in row['candidates']:
                if any(t and t in row['prompt'] + c['text'] for t in tok.all_special_tokens):
                    raise ValueError('Grafía de token especial en texto de recompensa')
                ids = tok.apply_chat_template([{'role':'user','content':row['prompt']},
                                               {'role':'assistant','content':c['text']}],
                                              tokenize=True, add_generation_prompt=False)
                if isinstance(ids, Mapping): ids = ids['input_ids']
                if not ids or len(ids) > meta['max_context']: raise ValueError('Respuesta completa no cabe en reward model')
                x = torch.tensor([ids], device='cuda')
                hidden = model(input_ids=x, attention_mask=torch.ones_like(x), use_cache=False,
                               return_dict=True).last_hidden_state[0, -1].float()
                c['reward'] = float((weight @ hidden).item())
                if not math.isfinite(c['reward']): raise ValueError('Recompensa no finita')
    del weight, model, base, tok; gc.collect(); torch.cuda.empty_cache()

def best_indices(candidates):
    # Primer máximo en caso de empate, con candidatos compartidos entre N.
    return {str(n): max(range(n), key=lambda i: candidates[i]['reward']) for n in NS}

def judge_scores(rows):
    if not torch.cuda.is_bf16_supported(): raise RuntimeError('El juez necesita bfloat16 en CUDA')
    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(ids) != 1 for ids in labels): raise ValueError('A y B no son tokens individuales')
    model = AutoModelForCausalLM.from_pretrained(JUDGE, revision=JUDGE_REV, local_files_only=OFFLINE,
                                                  dtype=torch.bfloat16, device_map={'':0}).eval()
    with torch.inference_mode():
        for row in rows:
            selected = best_indices(row['candidates'])
            row['selected'] = selected
            for n in NS:
                answer = row['candidates'][selected[str(n)]]['text']
                baseline = row['candidates'][0]['text']
                logits = []
                for first, second in ((answer, baseline), (baseline, answer)):
                    q = ('Choose the better answer to the user request. Reply with A or B only.\n'
                         'User request: ' + row['prompt'] + '\nAnswer A:\n' + first + '\nAnswer B:\n' + second)
                    if any(t and t in q for t in tok.all_special_tokens):
                        raise ValueError('Grafía de token especial en entrada del juez')
                    ids = tok.apply_chat_template([{'role':'user','content':q}], tokenize=True,
                                                  add_generation_prompt=True)
                    if isinstance(ids, Mapping): ids = ids['input_ids']
                    if len(ids) > 1024: raise ValueError('Par completo no cabe en el juez')
                    x = torch.tensor([ids], device='cuda')
                    pred = model(input_ids=x, use_cache=False).logits[0, -1]
                    logits.append(float(pred[labels[0][0]].float() - pred[labels[1][0]].float()))
                    if not math.isfinite(logits[-1]): raise ValueError('Salida del juez no finita')
                row.setdefault('judge', {})[str(n)] = {'ab':logits[0], 'ba':logits[1],
                                                      'selected_vs_first':(logits[0]-logits[1])/2}
    del model, tok; gc.collect(); torch.cuda.empty_cache()

def main():
    if not torch.cuda.is_available(): raise RuntimeError('Este laboratorio requiere CUDA')
    random.seed(SEED); np.random.seed(SEED); torch.manual_seed(SEED); torch.cuda.manual_seed_all(SEED)
    prompts, reward_report, prompts_sha, reward_report_sha = load_prompts()
    meta_path = REWARD / 'reward-meta.json'
    meta = json.loads(meta_path.read_text(encoding='utf-8'))
    OUT.mkdir(parents=True, exist_ok=True)
    rows, sft_hashes, sft_report_sha, sft_report = generate(prompts)
    reward_scores(rows, meta)
    judge_scores(rows)
    summary = []
    for n in NS:
        selected = [r['candidates'][r['selected'][str(n)]] for r in rows]
        margins = [r['judge'][str(n)]['selected_vs_first'] for r in rows]
        summary.append({'n':n, 'mean_reward':sum(c['reward'] for c in selected)/len(rows),
                        'judge_mean_margin':sum(margins)/len(rows),
                        'judge_win_tie_fraction':sum(1 if x > 0 else .5 if x == 0 else 0 for x in margins)/len(rows),
                        'kl_upper_bound_nats':kl_bound(n)})
    report = {'seed':SEED, 'quick':QUICK, 'n_prompts':len(rows), 'ns':NS,
              'generation':{'temperature':.8, 'top_p':.9, 'max_new_tokens':NEW_TOKENS,
                            'candidates_per_prompt':max(NS), 'same_candidates_across_n':True,
                            'tie_policy':'primer máximo'},
              'sft':{'checkpoint_sha256':sft_hashes, 'report_sha256':sft_report_sha,
                     'model':sft_report['model'], 'revision':sft_report['revision']},
              'reward':{'metadata':meta, 'metadata_sha256':file_hash(meta_path),
                        'head_sha256':file_hash(REWARD / meta['head_file']),
                        'adapter_weights_sha256':{p.name:file_hash(p) for p in (REWARD / 'adapter').glob('*.safetensors')},
                        'report_sha256':reward_report_sha},
              'prompts':{'file_sha256':prompts_sha, 'split':'test_prefs', 'source':reward_report['data']},
              'judge':{'model':JUDGE, 'revision':JUDGE_REV, 'dtype':'bfloat16',
                       'protocol':'Diferencia de logits A/B en ambos órdenes, comparado con primer candidato.'},
              'summary':summary, 'rows':rows, 'torch':str(torch.__version__),
              'limitations':'Juez automático, no verdad ni anotación humana. Test pequeño, una semilla; sin KL observada ni garantía de mejora general. La exclusión es por prompt exacto solo respecto al reward model, no prueba ausencia de contaminación del preentrenamiento o SFT.'}
    (OUT / 'best-of-n-report.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')
    for row in summary: print(json.dumps(row, ensure_ascii=False), flush=True)
    print('Informe:', OUT / 'best-of-n-report.json', flush=True)

if __name__ == '__main__': main()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

First run the SFT lab in m20-l15 and the reward-model lab in this lesson. Set ORYON_SFT_DIR and ORYON_REWARD_DIR to their folders and ORYON_BON_DIR for the report. Use ORYON_QUICK=1 only to check the flow and ORYON_OFFLINE=1 when models are already cached. It requires PyTorch, Transformers, PEFT, safetensors, NumPy and CUDA with bfloat16 for the judge. The Qwen2.5-3B-Instruct judge is a different open model from the reward model, with a pinned revision; it loads after the other models are released.

Candidates are generated once per prompt and their prefixes reused for every N. The reward for each prefix cannot decrease by construction. The judge compares the selected response with the first candidate in both orders; the logit difference is an automatic signal, not a human verdict or a measure of truth. The analytical KL bound is not a measured KL. Test prompts were excluded by exact match from reward-model training and validation, but this does not rule out prior policy contamination or paraphrases. A short test of two prompts cannot establish a general trend.

Exercises

This cell checks the Bradley-Terry probability and continuous KL expression. Use natural logarithms.

[ ]PythonBrowser
import math
ra, rb = 1.3, -0.4
probabilidad = 1 / (1 + math.exp(-(ra-rb)))
print("P(a sobre b):", probabilidad)
for n in (4, 10):
    print("KL continua, N =", n, ":", math.log(n) - (n-1)/n)
NumericFrom margin to probability
A reward model assigns 1.3 and −0.4 to two responses. Under Bradley-Terry with unit scale, what is the probability of preferring the first?
ProofFrom Gumbel to Bradley-Terry
Prove: Prove the preference probability induced by two utilities with Gumbel noise.
0
Let Ua = ra + εa and Ub = rb + εb, with independent standard Gumbel noise and F(t)=exp(−exp(−t)).

Step 1 of 3. How is the probability that a wins expressed?

ProofBest-of-N KL without ties
Prove: Derive the KL between the best-of-N selection policy and the base policy, assuming continuous scores.
0
The N responses are iid from the base policy and their score has continuous cumulative distribution F.

Step 1 of 3. What is the density ratio between the selected and base policies?

QuizCompare with human agreement
A reward model is correct on 72% of a dataset and inter-annotator agreement is 73%. Which conclusion is best supported?
CodePairwise loss and fitting
Implement reward_pair_loss(chosen, rejected) and fit_utilities(n, comparisons, steps=1200, lr=0.2). The first returns the mean softplus(rejected−chosen) for two nonempty, finite, equally shaped vectors, without overflow. The second receives n alternatives and (winner, loser) pairs; optimize their scores from zero by gradient descent on the mean loss plus 0.01·sum(r²)/2, centering to zero sum after each step. Reject invalid parameters, indices and vectors. The synthetic test data are noiseless and require generalizing the order to unseen pairs.
import numpy as np

def reward_pair_loss(chosen, rejected):
  pass

def fit_utilities(n, comparisons, steps=1200, lr=0.2):
  pass
Shift+Enter to run
Key idea

A preference is an observation conditional on a protocol. Bradley-Terry learns differences; selection with a proxy changes the distribution and may exploit its errors. Evaluate on held-out prompts, inspect agreement and length, and state the assumptions behind any KL calculation.