On-policy preferences and reward model
Generate multiple SFT-model answers per prompt and label them using available verifiers or a larger local judge, controlling for its biases. Train a Bradley-Terry reward model with LoRA on the pairs, measure test-pair accuracy, and establish the best-of-n baseline for DPO and GRPO.
After this lesson you can
- Generate on-policy answers and build pairs using verifiers or a calibrated judge.
- Implement the Bradley-Terry loss and train the reward model.
- Measure reward-model accuracy and sensitivity to length.
- Compute the best-of-n curve and its analytic KL bound relative to the policy.
Before you start
Reward is not the correct answer
The classifier in the previous lesson answers with a CWE identifier. An output may have the right format while naming the wrong weakness. If we ask the SFT model for several answers, a verifier can compare each identifier with the allowed labels for that advisory. This comparison produces concrete preferences: for the same advisory, a correct answer beats an incorrect one. There is no need to present these as human judgments or invent an expert who reviewed them.
On-policy preference generation takes candidates from the policy we want to improve. Their distribution depends on the template, temperature, sampling filters, generation limit, and checkpoint. Record all of these, as well as the seed, advisory identifier, and text of each output. Split the preference training set by advisory before forming pairs: if two answers to the same advisory end up in training and test sets, the result no longer measures generalization to new advisories. With temperature or top-p, the sampling distribution differs from the untransformed logits distribution; the best-of-n bound refers to the former.
For CWE, the verifier only knows whether the extracted identifier belongs to the valid labels. It cannot determine whether a free-form explanation is faithful, useful, or safe. Require one answer in the agreed format, treat ambiguous outputs as invalid, and retain ties without arbitrarily turning them into preferences. If you use a judge for criteria the verifier does not cover, evaluate both presentation orders, retain disagreements, and compare a sample against independent labels. Judge biases include favoring position or length even when overall accuracy appears high.
If an advisory has multiple valid labels in the catalog, do not turn a valid alternative into a rejected answer just because SFT chose the most specific label as the target. Record the labeling and evaluation rules separately: a strict labeler may reject additional text, while the p08-l04 protocol extracts the first CWE mention for scoring. Comparison with that baseline requires retaining its extractor and template.
Another separation matters: if preference prompts come from the SFT training set, splitting by prompt protects the reward-model test from memorizing its pairs, but does not make those prompts unseen by SFT. In CWE, several advisories may also belong to the same connected component of CVEs and text, as constructed in p08-l04. Assign the entire component to reward training or validation. The minimum identifier of each advisory is insufficient because it can differ within a component. Use CWE development data to select configurations and reserve the test set, separated in p08-l04, for the final report. Record the split used at each stage and do not use the test set to select hyperparameters.
The next cell reconstructs the components and all valid labels from the catalog saved in p08-l04. Set P08_L04_DIR to that run’s directory before starting the lab. The split check is recalculated here independently of each row’s IDs.
import collections, hashlib, json, os, re, zipfile
from pathlib import Path
import xml.etree.ElementTree as ET
folder = os.environ.get('P08_L04_DIR')
if not folder:
print('Define P08_L04_DIR con el directorio de p08-l04.')
else:
root = Path(folder)
archive = root / 'cwec_v5.0.xml.zip'
expected = 'bcda44c9abf61ff977f50c3c6649eea5a97a7b0626b0396c2c3ec4bfb973a3dc'
if hashlib.sha256(archive.read_bytes()).hexdigest() != expected:
raise ValueError('El catálogo no coincide con la versión fijada en p08-l04')
with zipfile.ZipFile(archive) as z:
catalog = ET.fromstring(z.read('cwec_v5.0.xml'))
ns = {'c': 'http://cwe.mitre.org/cwe-8'}
tokens = lambda s: re.findall(r'\w+', s.casefold())
norm = lambda s: ' '.join(tokens(s))
leak = re.compile(r'\s*\(?\bCWE-\d+\)?', re.IGNORECASE)
observed, usage = [], {}
for entry in catalog.findall('c:Weaknesses/c:Weakness', ns):
if entry.get('Status') == 'Deprecated':
continue
cid = int(entry.get('ID'))
usage[cid] = entry.findtext('c:Mapping_Notes/c:Usage', default='', namespaces=ns).strip()
for item in entry.findall('c:Observed_Examples/c:Observed_Example', ns):
ref = item.findtext('c:Reference', namespaces=ns).strip()
description = item.find('c:Description', ns)
text = ' '.join(''.join(description.itertext()).split()) if description is not None else ''
text = ' '.join(leak.sub('', text).split())
if len(tokens(text)) >= 4:
observed.append((ref, text, cid))
counts = collections.Counter(cid for _, _, cid in observed)
labels = {cid for cid, count in counts.items() if count >= 8
and usage[cid] in ('Allowed', 'Allowed-with-Review')}
observed = [(ref, text, cid) for ref, text, cid in observed if cid in labels]
parent = {}
def find(key):
parent.setdefault(key, key)
while parent[key] != key:
parent[key] = parent[parent[key]]
key = parent[key]
return key
for ref, text, _ in observed:
parent[find(('cve', ref))] = find(('txt', norm(text)))
groups = collections.defaultdict(list)
for ref, text, cid in observed:
groups[find(('cve', ref))].append((ref, text, cid))
component, gold = {}, collections.defaultdict(set)
for group in groups.values():
name = min(ref for ref, _, _ in group)
for _, text, cid in group:
component[norm(text)] = name
gold[norm(text)].add(cid)
train = json.loads((root / 'train.json').read_text(encoding='utf-8'))
dev = json.loads((root / 'dev.json').read_text(encoding='utf-8'))
test = json.loads((root / 'test.json').read_text(encoding='utf-8'))
def fingerprint(value):
data = json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(',', ':')).encode('utf-8')
return hashlib.sha256(data).hexdigest()
expected_dev = '81526ee6b5e425359590190d36d9440a22d2ae106d1a24ac22a9542a525c23cf'
expected_test = 'fa0bd7c5a680bcb1e41e52de25863d84ad608b7507d9fd882eb05cf28340a407'
if fingerprint(dev) != expected_dev or fingerprint(test) != expected_test:
raise ValueError('El examen congelado no coincide con el protocolo de p08-l04')
train_groups = {component[norm(row['evidence'])] for row in train if row['kind'] == 'clasificar'}
dev_groups = {component[norm(row['text'])] for row in dev}
test_groups = {component[norm(row['text'])] for row in test}
assert not (train_groups & dev_groups or train_groups & test_groups or dev_groups & test_groups)
(root / 'componentes.json').write_text(json.dumps(component, ensure_ascii=False), encoding='utf-8')
(root / 'multi-gold.json').write_text(json.dumps({k: sorted(v) for k, v in gold.items()}, ensure_ascii=False), encoding='utf-8')
print('componentes de clasificación:', len(train_groups), '· desarrollo:', len(dev_groups), '· prueba:', len(test_groups))
print('separación por componentes: correcta')npm run lab and open the connection link.Reconstructing the fixed catalog yields 823 classification components, 116 development components, and 233 test components. Some components contain multiple advisories, so reward-model and best-of-n intervals must resample complete components. Reward-model training data contain only answers generated by SFT for those inputs; no development or test examples are added to training pairs.
A new generation run using the reconstructed SFT and 16 candidates per advisory produced 13,456 answers for 841 classification advisories. Under the strict verifier, 484 advisories had both correct and incorrect answers, 336 had only correct answers, and 21 had only incorrect ones. These count advisories, not components or independent pairs. The adapter used is a short rerun of the configuration chosen in p08-l04, not the lost historical checkpoint. Subsequent reward-model results must come from its own training and cannot be inferred from these counts.
Local lab: preferences and reward
First complete p08-l04, retain its directory with adapter adaptadores/r64-att-0.0002, and run the previous cell to create componentes.json and multi-gold.json. Download preferencias.py and use a new output directory. The script requires a CUDA GPU and looks in the local cache for Qwen/Qwen2.5-0.5B-Instruct at revision 7ae557604adf67be50417f59c2c2f167def9a775. If missing, download it beforehand using huggingface_hub.snapshot_download with that revision. The measured run used Python 3.12, PyTorch 2.11.0+cu128, transformers 5.23.0, and peft 0.21.3; record the actual versions in your environment.
In PowerShell, replace the paths with your own and run the downloaded file:
$env:P08_L04_DIR = 'C:\ruta\a\salida-p08-l04'
$env:P08_PREFERENCES_DIR = 'C:\ruta\a\preferencias-nuevas'
python preferencias.py
Generation saves partial batches and a manifest so they can be resumed with the same code, adapter, and data. Fine-tuning creates reward_adapter, reward_head.pt, and losses.json; it does not overwrite an existing reward model. results.json contains validation, length analysis, and a development curve for the figure. This script does not save intermediate checkpoints during fine-tuning, so keep its outputs and allow enough time to complete the epoch. Your result depends on your SFT and environment. The published JSON belongs to the run described here and does not promise an exact match.
From comparisons to scores
A Bradley-Terry reward model assigns a scalar to an answer for prompt . For two answers it proposes
The scalar head reads the representation of the last valid dialogue token, not a padding position. The body may use LoRA while the remainder stays frozen. For each chosen and rejected pair, the negative log-likelihood loss is ; minimizing its mean performs maximum-likelihood fitting. This form avoids overflow for large margins. Adding a constant dependent on to both scores changes no probability, so comparisons do not identify the score origin. Multiplying the margins, however, changes the Bradley-Terry probabilities if the logistic scale stays fixed.
Derive the update to see what it learns. If , then and . A misordered pair has a derivative close to and pushes strongly to increase the margin. A correctly ordered pair with a large margin has a derivative close to zero. A confident but wrong label keeps pushing in the wrong direction, which makes pair quality especially important.
For example, scores 1.2 and 0.4 give margin 0.8, preference probability 0.689974, and loss 0.371101 nats. The derivative with respect to the margin is approximately -0.310026. Changing the scores to 11.2 and 10.4 preserves all three values: the comparison model sees only their difference. Doubling the margin with a fixed logistic scale increases confidence and decreases loss. Distinguish the unidentifiable per-prompt shift from the margin scale, which affects the predicted probability.
Pairwise accuracy loses some information. Two heads may order the same pairs correctly while producing probabilities of 0.55 and 0.99 respectively. The first is less confident and the second receives a much larger penalty when wrong. Log-likelihood rewards both ordering and confidence. An extreme score can improve loss on a correctly labeled pair while making it much worse on another with a noisy label. This motivates separate training, validation, and evaluation, rather than choosing the head only because it achieves the lowest loss on its training pairs.
How pairs are constructed also changes the effective objective. Sixteen answers to one advisory, one correct and fifteen incorrect, can yield fifteen different pairs, but all share the same positive answer. Treating them as fifteen independent observations exaggerates the evidence. Limiting or weighting pairs per advisory reduces domination by one prompt; estimating uncertainty still requires resampling the original group, not its individual pairs. If two advisories belong to the same catalog component, evaluation grouping must cover the entire component.
The head needs its own gradients: accidentally freezing its parameters leaves only a fixed random projector. Also inspect which transformer parts are trainable, because a PEFT configuration that leaves embeddings or normalizations open changes the experiment’s budget. A pair shares a prompt across both branches, but each branch has its own answer tokens and attention mask. With right padding, the readout index is the last unpadded position of each sequence, not necessarily the batch’s last column.
If the head is , its bias cancels exactly when subtracting scores within a pair, so Bradley-Terry cannot identify it from these comparisons. Initializing to zero makes all initial margins zero and the loss . On that first step, the gradient to representation passes through and is zero, although the head can receive a gradient if chosen and rejected representations differ. After updating , the gradient to the body can be nonzero. A zero first LoRA gradient under this initialization alone does not establish that the adapter is disconnected: check the head and subsequent steps.
import numpy as np
chosen_h = np.array([1., 2.])
rejected_h = np.array([0., 1.])
w = np.zeros(2)
margin = w @ (chosen_h - rejected_h)
dmargin = 1 / (1 + np.exp(-margin)) - 1
grad_w = dmargin * (chosen_h - rejected_h)
grad_chosen_h = dmargin * w
grad_bias = dmargin * (1 - 1)
print('cabeza:', grad_w, '· representación:', grad_chosen_h, '· sesgo:', grad_bias)
assert np.allclose(grad_w, [-0.5, -0.5]) and np.allclose(grad_chosen_h, 0) and grad_bias == 0Before training the full model, compare the loss with RewardTrainer from TRL 1.19.0 on two fixed pairs. Use an isolated local environment with PyTorch and that TRL version; the test ran with PyTorch 2.11.0 and transformers 5.23.0. Its model returns known scores, and the TRL class only computes loss and metrics. Direct access to compute_loss isolates the arithmetic and does not replace actual training.
import importlib.metadata
from collections import defaultdict
from types import SimpleNamespace
import torch
import torch.nn.functional as F
from trl import RewardTrainer
if importlib.metadata.version('trl') != '1.19.0':
raise RuntimeError('Esta comprobación usa TRL 1.19.0')
class IdentityAccelerator:
def gather(self, value): return value
def gather_for_metrics(self, value): return value
class Fixed(torch.nn.Module):
def forward(self, **inputs):
# TRL espera primero las elegidas y después las rechazadas.
return SimpleNamespace(logits=torch.tensor([[1.2], [0.5], [0.4], [-0.2]], dtype=torch.float64))
model = Fixed().eval()
trainer = RewardTrainer.__new__(RewardTrainer)
trainer.model = model
trainer.args = SimpleNamespace(center_rewards_coefficient=None)
trainer.accelerator = IdentityAccelerator()
trainer._metrics = {'train': defaultdict(list), 'eval': defaultdict(list)}
trainer._total_train_tokens = 0
trainer._tp_size = 1
actual = trainer.compute_loss(model, {'attention_mask': torch.ones(4, 2, dtype=torch.long)})
own = F.softplus(torch.tensor([0.4 - 1.2, -0.2 - 0.5], dtype=torch.float64)).mean()
print('TRL:', actual.item(), '· propia:', own.item(), '· diferencia:', abs(actual.item() - own.item()))
assert torch.allclose(actual, own, atol=1e-12, rtol=0)npm run lab and open the connection link.The loss is approximately 0.387143 in both implementations. This check uses an internal API and a pinned version; training and evaluation must then be compared using real data.
Accuracy counts the fraction with on test advisories. Ties need an explicit convention rather than being accidentally counted as successes. Also measure calibration, for example by grouping predicted probabilities and comparing them with observed frequencies. An interval computed by pair can be too narrow if pairs share a prompt or component. Resample whole components and keep their pairs together. Distinguish overall pairwise accuracy from the mean giving each component equal weight. For length bias, record both answer lengths, their correlation with reward, and accuracy on subsets where the chosen answer is shorter or longer. Correlation alone does not establish causality.
RewardBench collects conversation, reasoning, and safety comparisons, including pairs with subtle verifiable errors. It reminds us that accuracy on one set of pairs is insufficient to characterize a reward model. Our CWE set evaluates a different, specific distribution and does not inherit that benchmark’s scores.
Calibration requires a convention for ordering. If the chosen answer always appears first, all observed labels are one and a naive plot does not represent a mixture of wins and losses. You can also reverse each pair, with predicted probability and label zero. When estimating uncertainty, both orientations still belong to the same prompt. A generative judge must also see each pair in both orders: disagreement on reversal is an unresolved result, not a win to allocate arbitrarily.
A model can rank well and still be poorly calibrated. Suppose it gets eight of every ten comparisons assigned probability 0.99 correct: its ranking may be useful, but its stated confidence is excessive. Group predictions from a held-out split and compare average confidence with observed frequency in each group. Also provide the number of pairs and components in each interval, since an extreme frequency in a small group may just be noise. Calibration refers to the process that produced those pairs and labels; it does not guarantee equal reliability on answers from another model or on criteria the verifier does not measure.
For length analysis, a correlation between score and token count mixes differences across prompts and answers. Also examine length differences within pairs, accuracy when the chosen answer is shorter or longer, and examples with high scores but incorrect labels. If the model rewards a repetitive string, best-of-n may find that weakness more often as increases. This analysis alone does not identify a cause: a longer answer may contain useful information as well as triggering a spurious judge preference.
A more direct control preserves the essential answer and changes only the feature under investigation, for example adding a neutral sentence that does not change the CWE identifier. Evaluate both versions under the same prompt and record the score difference. A consistent change reveals sensitivity to that specific modification; it does not establish that every preference for longer answers is wrong or that other sentences have the same effect. Use held-out examples or separately prepared controls and specify exactly what text was added.
The labeler and reward model can fail in different ways. In CWE, the strict pair-construction rule marks an ambiguous or malformed answer invalid even if it later contains a correct label. The historical evaluation extractor instead looks for the first CWE mention. This deliberate difference is declared so that training-signal cleanup is not confused with the domain metric comparable to SFT. Improvement under one criterion does not necessarily imply improvement under the other; save raw outputs so both can be applied without regenerating them.
When inspecting a selection curve, compare the starting point with larger values on the same advisories. The chosen answer’s average score may increase by construction, but accuracy depends on how the head ranks correct and incorrect answers. An interval over components reflects variation among development advisories; it does not automatically include variation from retraining the reward model with another seed. To quantify that second source of uncertainty, repeat independent fits and record both levels rather than presenting permutations of one sample as new advisories.
Pair coverage describes the population on which the head is trained. If all samples for an advisory are correct, all incorrect, or identical, no pair has a verifiable win under this criterion. Count these groups separately and publish the fraction that does generate a pair. Reward-model accuracy on retained pairs does not automatically describe discarded advisories. Many pairs may also come from one advisory: reporting the mean per component as well as per pair prevents a prolific group from dominating interpretation.
Selecting among multiple samples
The best-of-n baseline generates independent answers from the same policy and returns the one with greatest reward. It is a new policy even without gradients or weight updates. To compare it with a trained policy, include the cost of generating and scoring answers, keep the same set of prompts, and use an evaluation external to the reward model.
If experiments are coupled by using the same infinite sequence of samples and taking its first , the maximum reward never decreases when a sample is added. This monotonicity follows from the selection rule and does not prove better behavior. An imperfect reward can rank an incorrect answer higher, giving the selector more opportunities to exploit it as grows. Specify tie-breaking too: random choice, first occurrence, or length can produce different distributions.
Proof
In the continuous case, is uniform on . The probability that the other scores are smaller is , so the density of the selected output relative to is . The selected variable has density and, by integration, . Therefore the KL is .
With atoms, add an independent uniform tie-breaker to each sample and order lexicographically by score and tie-breaker. The randomized rank is uniform, and the same calculation gives the expression for the joint distribution of answer and tie-breaker. Discarding the tie-breaker cannot increase divergence by the data processing inequality for KL. This proves the bound, but not necessarily equality, for the answer alone.
∎This bound is not a quality measure. Gao, Schulman, and Hilton studied a proxy reward and a synthetic reference reward: optimizing the former too strongly can worsen the latter. These were not human annotations, and that finding does not establish that our CWE curve must have the same shape. This lesson’s curve must come from the actual run and show both learned reward and verifiable accuracy.
The plot calculates an exact four-case model: success or failure, each with high or low score. If the probability of a high score is , a selection of samples has a high score with probability . Conditional on at least one high score, accuracy is the fraction correct among high-scored samples; otherwise it is the fraction among low-scored samples. Ties are broken uniformly. You can even create an inverted judge: if it scores failures highly more often than successes, selecting more samples decreases quality.
The following figure starts with results from one actual run and lets you load the results.json of another. The bound shown when selecting is analytic; it is not a KL estimate from answers. The results file and its provenance retain the values, revisions, and hashes used in the figure.
The reward model was trained for one epoch on 1532 pairs and evaluated on 404 pairs from 100 held-out components. Mean accuracy per component was 65.5%, with 95% bootstrap interval [56.3%, 74.5%]; pairwise accuracy was 65.8%. These advisories come from the set used to build SFT, although their components are separate from head training. Correlation between score and length of development candidates was -0.166: it describes this sample and does not identify a cause.
On the 117 CWE development advisories, selected reward increased from -0.152 at to 0.200 at , while accuracy fell from about 66.7% to 59.8%. The curve averages 64 permutations of the 16 candidates per advisory and per value; intervals resample the 116 development components. Exact accuracy for a candidate selected uniformly from the 1872 generated is 1253/1872, or 66.93%. The small difference from the point is due to the Monte Carlo approximation. The observed drop illustrates the need for an external metric, but this run alone does not establish statistical significance or recurrence on test data or other seeds.
import math
def best_binary(p, n):
q = 1 - (1 - p) ** n
kl = q * math.log(q / p) + (1 - q) * math.log((1 - q) / (1 - p)) if q < 1 else math.log(1 / p)
return q, kl, math.log(n) - (n - 1) / n
for n in (1, 2, 4, 8, 16):
q, kl, bound = best_binary(0.25, n)
print(f'n={n:2d}: éxito={q:.4f}, KL={kl:.4f}, cota={bound:.4f}')This example is an analytic model: each sample is correct with probability 0.25 and the selector recognizes correctness perfectly. A real reward need not recognize it, and equality does not hold here because of binary ties. It does not replace the lab measurement.
Exercises
import numpy as np
def bt_loss(chosen, rejected):
...Step 1 of 2. What is the distribution of a sample's randomized rank?