RLHF with PPO
Derive token-level RLHF and study PPO, GAE, KL control, reward overoptimization, and practical evaluation.
After this lesson you can
- Write the RLHF objective, reward minus β·KL, and decompose it into token rewards.
- Formulate text generation as a token-level MDP with terminal reward and a KL penalty at each step.
- Implement PPO for an LLM from scratch: rollouts, reference log-probs, values, GAE, clipped loss and value loss.
- Fit policy, reference, value and reward into 8 GB using LoRA and obtain the reference by disabling the adapter.
- Measure overoptimization by comparing proxy and reference reward against KL and apply mitigations.
Before you start
- 20Reward modelBradley-Terry modelBest-of-N samplingReward model evaluationLow-Rank Adaptation
- 22PPO clipped objectiveAdvantage functionActor-criticGeneralized advantage estimationPolicy gradient theoremREINFORCEBaselines for variance reduction
- 07KL-regularized optimizationGibbs variational principleMonte Carlo KL estimators
- 21Temperature samplingNucleus (top-p) sampling
From imitating responses to optimizing preferences
Supervised fine-tuning teaches a model to continue examples. A reward model learns to rank responses according to available comparisons. How can you change the policy so it produces better-rated responses itself, without moving so far from the distribution where the evaluator is reliable? Reinforcement learning offers an approximate answer: generate, score and update, but each part introduces choices that must be measured.
Ziegler and colleagues and Stiennon and colleagues studied human-preference fine-tuning for generation and summarization. In InstructGPT, the authors found that their 1.3 billion parameter model’s responses were preferred to those of 175 billion parameter GPT-3 on the evaluated prompt distribution. The result depends on that evaluation and does not mean the smaller model outperforms the larger one at every task.
Reward and the price of deviation
For an instruction , a complete response , a fixed reference and a reward model , the KL-regularized RLHF objective is
The reference is usually the frozen starting SFT model. KL in nats penalizes distribution changes; it does not guarantee quality or safety. Its scale depends on the prompt distribution and treatment of length; do not compare a sequence-level objective with a mean per-token measurement without converting units. expresses a tradeoff in units of : multiplying all rewards by a constant without changing changes the problem.
In a finite response space, restricting to the reference support, define . Then
The identity proves optimality of without assuming PPO reaches it. Querying for every response and calculating is intractable in open-ended generation: the solution describes the objective, not a practical exact sampling algorithm. The Gibbs variational identity allows the same relationship to be studied more generally.
A response as a trajectory
In the token-level MDP, state contains the prompt and prefix, the action is and the transition appends that token. If EOS ends the response and the same policy is used to generate and evaluate its probabilities, the chain rule gives
For each trajectory, distribute across its tokens and add to the final token. With , the expected sum exactly matches the sequence-level objective. An individual log-ratio sample can be negative even though expected KL is nonnegative. Discounting with changes the weighting of terms and no longer represents the same decomposition.
The distributed reward depends on the policy. Objective equality applies to trajectories from that same policy; freezing rewards and log probabilities for several PPO epochs yields an approximation using old data, not equality for every updated policy. Length-truncated generation needs an explicit criterion: if it is only a time cutoff, retain the estimated next-state value; if you define a finite horizon ending there, use zero terminal value and acknowledge that the task changed. Real EOS, artificial cutoff and padding are three different things.
The sequence in this cell is an algebraic example, not a neural-network rollout. Each state has two actions; given probabilities are for the selected one and the alternative receives the complement. A local bonus of 1.2 is added to the last observed token for both EOS and cutoff to isolate the bootstrap difference; at cutoff this does not imply the episode has ended. With EOS the next state is terminal; at cutoff its value is retained. Padding contributes neither reward nor advantage.
The controller uses explicit toy dynamics, different from a measured PPO training run. The coefficient is updated with a bounded relative error and KL response follows an equation chosen to study feedback; neither assumes universal convergence. The reward reading is the chosen function R = log(1 + KL), increasing with KL and not intended to describe a real policy.
import math
tokens = ['La', 'trama', 'fue', 'genial']
policy = [.60, .45, .70, .55]
reference = [.50, .60, .50, .50]
values = [.60, .50, .35, .20, .30, 0.]
def gae(rewards, values, mask, terminal, gamma, lam):
if len(values) != len(rewards) + 1 or len(mask) != len(rewards) or len(terminal) != len(rewards):
raise ValueError('Dimensiones incompatibles')
result = [0.] * len(rewards)
carry = 0.
for t in range(len(rewards) - 1, -1, -1):
if not mask[t]:
carry = 0.
continue
delta = rewards[t] + gamma * (0 if terminal[t] else values[t + 1]) - values[t]
continues = t + 1 < len(mask) and mask[t + 1] and not terminal[t]
carry = delta + (gamma * lam * carry if continues else 0.)
result[t] = carry
return result
def rollout(beta=.2, gamma=1., lam=.95, length=4, eos=True):
if not 1 <= length <= 4: raise ValueError('Longitud inválida')
mask = [i < length for i in range(5)]
terminal = [active and eos and i == length - 1 for i, active in enumerate(mask)]
ratios = [math.log(p/q) for p, q in zip(policy, reference)]
rewards = [(-beta * ratios[i] + (1.2 if i == length - 1 else 0)) if mask[i] else 0.
for i in range(5)]
return {'mask': mask, 'terminal': terminal, 'ratios': ratios, 'rewards': rewards,
'advantages': gae(rewards, values, mask, terminal, gamma, lam)}
def controller(target=.4, horizon=200, adaptive=True, steps=80):
if target <= 0 or horizon <= 0: raise ValueError('Objetivo y horizonte deben ser positivos')
kl, beta = .2, 1.
rows = [(0, kl, beta, math.log1p(kl))]
for step in range(1, steps + 1):
error = max(-.2, min(.2, kl/target - 1))
if adaptive: beta *= 1 + error * min(10/horizon, 1)
kl += .25 * (1.2/(1 + beta) - kl)
rows.append((step, kl, beta, math.log1p(kl)))
return rows
eos = rollout(); truncated = rollout(eos=False)
assert eos['advantages'][-1] == truncated['advantages'][-1] == 0
assert abs((truncated['advantages'][3] - eos['advantages'][3]) - .30) < 1e-12
zero_discount = rollout(gamma=0)
assert all(abs(zero_discount['advantages'][i] - (zero_discount['rewards'][i] - values[i])) < 1e-12 for i in range(4))
mc = rollout(beta=0, gamma=1, lam=1)
assert abs(mc['advantages'][0] - (1.2 - values[0])) < 1e-12
short = rollout(length=2, eos=False)
assert short['mask'] == [True, True, False, False, False]
assert short['advantages'][2:] == [0., 0., 0.]
fixed = controller(adaptive=False); adaptive = controller(adaptive=True)
assert all(b == 1 for _, _, b, _ in fixed)
assert all(k >= 0 and b > 0 and abs(r - math.log1p(k)) < 1e-15 for _, k, b, r in adaptive)
assert abs(fixed[-1][1] - .6) < 1e-10
print('Log π/ref:', eos['ratios'])
print('Recompensas con máscara:', eos['rewards'])
print('Ventajas EOS:', eos['advantages'])
print('Ventajas truncamiento:', truncated['advantages'])
print('Control adaptativo, paso 80 (paso, KL, β, recompensa):', adaptive[-1])
print('Control fijo, paso 80 (paso, KL, β, recompensa):', fixed[-1])
print('Comprobadas: máscara, EOS, truncamiento, γ=0 y retorno completo con λ=1.')Advantages and proximal update
A value head estimates and reduces variance. For an indicator equal to one only when the transition ends the episode, GAE advantages are calculated backwards:
At a bootstrapped cutoff, is incorporated into , but the observed recursion does not continue beyond collected data. Neither advantage nor loss is computed on padding. In terminal episodes with and , advantage is the full return minus , so recovers that return. Smaller values of trade variance for dependence on the value approximation.
The adaptation of PPO to language retains the policy that generated the batch as . For every valid token it computes and maximizes the masked mean of
Add a regression loss for and, if appropriate, an entropy term. The SFT reference and old policy play different roles: the former fixes the cost of deviation and the latter defines the update ratio. Store old log probabilities during generation; recomputing them after updating would destroy that comparison. PPO clipping does not impose a strict bound on total KL, particularly after several epochs or with shared parameters.
Normalizing advantages over valid tokens changes gradient scale and, with batch centering, can change individual signs. Normalizing rewards or values also changes scales: record statistics and apply the same protocol across comparisons. Use separate learning rates or parameter groups for policy and value, and check their losses and gradient norms. If they share a backbone, a value update can move the policy too.
Temperature and filters are part of the effective distribution. If sampling with temperature , calculate both old and new log probabilities with the same transformation. Top-p can change support during an update, leaving actions possible under one distribution outside the other; this invalidates standard importance-ratio assumptions. For the lab use full softmax and record temperature, attention mask, EOS and length limit.
Huang and colleagues document details of an RLHF reproduction for summarization: their table 7 includes, among other choices, , , PPO clipping of and temperature . These are hyperparameters of that experiment, not universally optimal values. Try multiple seeds and record the fraction of responses reaching the limit without EOS. A nontermination penalty can help if defined by the protocol, but changes the reward and must be applied consistently in training and evaluation.
What does controlling KL mean?
Adaptive KL control changes according to observed distance from a target: when KL exceeds the budget it can increase deviation cost; when below it can reduce it. Horizon and batch size govern correction speed. This is no stability guarantee: sampling noise, delay, policy changes and different sequence scales all occur.
The simulation above explicitly defines its own response to ; it helps reason about a controller, not predict PPO convergence. Record KL against SFT, KL between new and old policies, clipped ratio fraction, entropy, lengths and rewards separately. Low training KL does not prove external reward improved.
Three estimators, three distinct uses
Let be the policy and the reference, both normalized on the same support, and for . Then has expectation , although it may be negative in a sample. is a nonnegative local approximation, generally biased. is nonnegative by and has the same expectation as because . If the reference has mass outside the support of , this equality fails. See Schulman’s notes and KL estimators.
Estimating KL and differentiating it are different things. Using as frozen reward on old-policy trajectories does not guarantee the exact gradient of current-policy KL. The lab uses signed per-token log-ratio as reward collected in the rollout and logs KL separately. If introducing a differentiable loss penalty, derive the estimator’s gradient and verify the distribution under which it is averaged; do not swap formulas merely because their expectations coincide at one point.
Run PPO on a limited GPU
The lab keeps a frozen base and trains a LoRA adapter for the policy. The reference is obtained by disabling the adapter on that same SFT base, without storing a second full copy of weights. This equivalence requires the base to actually be the reference, no other shared weights to be modified, and the value head not to change its logits. Numerically verify reference logits before and after training. The value head and sentiment classifier have their own memory requirements; batch rollouts and scores and release unused tensors.
This lab applies PPO to continuations of fictional reviews. First run m20-l15 SFT and retain sft-report.json and the final/ directory; ORYON_SFT_DIR must point to that folder. PPO loads those weights as the base and adds an initially zero LoRA adapter. Disabling it gives the frozen SFT reference and checks its complete distribution before and after each update. The value head is a separate trainable scalar layer.
The default classifier is DistilBERT fine-tuned on SST-2, revision 714eb0fa89d2f80546fda750413ed43d93601a13. The terminal reward is its positive-sentiment probability for the continuation, not a human quality judgment. The report records classifier truncations at 512 tokens. You can also point to an m20-l18 reward model via ORYON_REWARD_DIR; the base, adapter and head fingerprints are then checked and its unpadded template used. In both cases, a trajectory reaching the horizon without EOS ends as a finite episode, receives terminal reward and a 0.2 penalty; next value is zero, not interpreted as an infinite continuation.
Sampling uses the full softmax distribution at temperature 1, without top-k or top-p. Old probabilities are saved during generation and checked by a second evaluation before optimization; reference and new probabilities use the same temperature. Sampled per-token KL is the log probability ratio and can be negative in one sample; it is not replaced by its absolute value. Rollouts are unpadded sequences, while GAE also accepts right-padding masks. Advantages are normalized over valid tokens, and old values, returns and advantages are fixed during PPO epochs. The policy remains in evaluation mode to avoid dropout discrepancies, but LoRA gradients remain active.
Set ORYON_QUICK=1 for two rollouts, a maximum of eight tokens and one update with two epochs; full mode uses eight rollouts, at most 48 tokens and 80 updates with four epochs. These are experimental configurations, not a promise of improvement. ORYON_PPO_BETA sets the initial penalty, default 0.1. Adaptive KL control is optional with ORYON_PPO_ADAPT_KL=1; ORYON_PPO_KL_TARGET and ORYON_PPO_KL_HORIZON set the per-sequence target and horizon. Use ORYON_PPO_PROMPTS for training JSONL with prompt and prompt_id, and reserve other prompts for evaluation. ORYON_PPO_DIR selects output: each checkpoint stores adapter, value head and manifest with fingerprints, sampling policy and reference; ppo-report.json retains tokens, rewards, advantages, entropy and sampled KL. With ORYON_OFFLINE=1 models must already be cached. Install torch, transformers, peft, huggingface_hub, safetensors and numpy; the code requires CUDA. Implementations follow PPO and GAE, with generation and evaluation details made explicit here.
"""PPO de tokens con base SFT congelada, LoRA y recompensa verificable."""
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 huggingface_hub import snapshot_download
from peft import LoraConfig, PeftModel, get_peft_model
from safetensors.torch import load_file, save_file
from transformers import AutoModel, AutoModelForCausalLM, AutoModelForSequenceClassification, AutoTokenizer
QUICK = os.getenv('ORYON_QUICK') == '1'
OFFLINE = os.getenv('ORYON_OFFLINE') == '1'
SFT = Path(os.getenv('ORYON_SFT_DIR', './oryon-sft'))
OUT = Path(os.getenv('ORYON_PPO_DIR', './oryon-ppo'))
REWARD_DIR = os.getenv('ORYON_REWARD_DIR', '')
PROMPTS = os.getenv('ORYON_PPO_PROMPTS', '')
SENTIMENT = 'distilbert/distilbert-base-uncased-finetuned-sst-2-english'
SENTIMENT_REV = '714eb0fa89d2f80546fda750413ed43d93601a13'
SEED = 1919
TAU = 1.0
BETA = float(os.getenv('ORYON_PPO_BETA', '.1'))
GAMMA, LAMBDA, CLIP = 1., .95, .2
MAX_NEW = 8 if QUICK else 48
ROLLOUTS = 2 if QUICK else 8
UPDATES = 1 if QUICK else 80
EPOCHS = 2 if QUICK else 4
NO_EOS_PENALTY = .2
EOS = (0, 2)
ADAPT_KL = os.getenv('ORYON_PPO_ADAPT_KL') == '1'
KL_TARGET = float(os.getenv('ORYON_PPO_KL_TARGET', '1.0'))
KL_HORIZON = int(os.getenv('ORYON_PPO_KL_HORIZON', '100'))
if not math.isfinite(BETA) or BETA < 0: raise ValueError('ORYON_PPO_BETA debe ser finito y no negativo')
if not math.isfinite(KL_TARGET) or KL_TARGET <= 0 or KL_HORIZON <= 0: raise ValueError('Objetivo y horizonte KL deben ser positivos')
torch.set_num_threads(1)
def file_hash(path):
h = hashlib.sha256()
with open(path, 'rb') as f:
for block in iter(lambda: f.read(1024*1024), b''): h.update(block)
return h.hexdigest()
def hashes(directory):
return {p.name:file_hash(p) for p in sorted(Path(directory).glob('*.safetensors'))}
def gae(rewards, values, mask, gamma=1., lam=.95):
r, v, m = np.asarray(rewards, float), np.asarray(values, float), np.asarray(mask, bool)
if r.shape != v.shape or r.shape != m.shape or r.ndim != 2: raise ValueError('Formas incompatibles')
if np.any(m[:,1:] & ~m[:,:-1]): raise ValueError('La máscara debe ser contigua y rellenar por la derecha')
out = np.zeros_like(r); carry = np.zeros(r.shape[0])
for t in reversed(range(r.shape[1])):
next_mask = m[:,t+1] if t+1 < r.shape[1] else np.zeros(r.shape[0], bool)
next_value = v[:,t+1] if t+1 < r.shape[1] else np.zeros(r.shape[0])
delta = r[:,t] + gamma * next_value * next_mask - v[:,t]
carry = (delta + gamma * lam * carry * next_mask) * m[:,t]
out[:,t] = carry
return out, (out + v) * m
def plain_ids(tok, text):
if any(t and t in text for t in tok.all_special_tokens): raise ValueError('Token especial en el prompt')
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 prompt no recupera su texto exactamente')
return ids
def prompt_ids(tok, text):
# Misma plantilla explícita del SFT de l15, sin usar su código ni ficheros temporales.
start, end = tok.convert_tokens_to_ids('<|im_start|>'), tok.convert_tokens_to_ids('<|im_end|>')
if (start,end) != (1,2): raise ValueError('Se esperaba la plantilla SmolLM2 de l15')
return ([start] + plain_ids(tok, 'user\n') + plain_ids(tok, text) + [end]
+ plain_ids(tok, '\n') + [start] + plain_ids(tok, 'assistant\n'))
def prompts():
if PROMPTS:
with open(PROMPTS, encoding='utf-8') as f: rows = [json.loads(line) for line in f if line.strip()]
if not rows or any(not isinstance(r.get('prompt'),str) or not r['prompt'] for r in rows):
raise ValueError('El JSONL debe contener prompts no vacíos')
return [{'prompt':r['prompt'], 'prompt_id':r.get('prompt_id') or hashlib.sha256(r['prompt'].encode()).hexdigest()} for r in rows]
return [{'prompt_id':str(i), 'prompt':p} for i,p in enumerate([
'Write a short positive review of a fictional film.',
'Describe an uplifting fictional movie in a few sentences.',
'Write a warm review of a fictional comedy.',
'Describe a fictional film with a hopeful ending.'])]
def stats(model, head, prefix, actions, reference=False):
ids = torch.tensor([prefix + actions], dtype=torch.long, device='cuda')
manager = model.disable_adapter() if reference else None
if manager is not None: manager.__enter__()
try:
result = model(input_ids=ids, use_cache=False, output_hidden_states=True, return_dict=True)
start = len(prefix)-1; end = start + len(actions)
logits = result.logits[0,start:end].float() / TAU
logp = torch.log_softmax(logits, dim=-1)
selected = logp.gather(1, torch.tensor(actions, device='cuda')[:,None]).squeeze(1)
entropy = -(logp.exp()*logp).sum(dim=-1)
value = head(result.hidden_states[-1][0,start:end].float()).squeeze(-1)
return selected, value, entropy
finally:
if manager is not None: manager.__exit__(None, None, None)
def reference_probe(model, prefix, actions):
# Compara toda la distribución en la misma secuencia, no solo el token muestreado.
with torch.no_grad(), model.disable_adapter():
ids = torch.tensor([prefix + actions], dtype=torch.long, device='cuda')
logits = model(input_ids=ids, use_cache=False, return_dict=True).logits[0]
start = len(prefix)-1
return torch.log_softmax(logits[start:start+len(actions)].float()/TAU, dim=-1).cpu()
def rollout(model, head, tok, item, generator):
prefix = prompt_ids(tok, item['prompt']); actions = []; log_old = []; old_value = []; old_entropy = []
if len(prefix) + MAX_NEW > model.config.max_position_embeddings:
raise ValueError('El prompt y el horizonte exceden el contexto de la política')
model.eval(); head.eval()
with torch.no_grad():
for _ in range(MAX_NEW):
out = model(input_ids=torch.tensor([prefix+actions], device='cuda'), use_cache=False,
output_hidden_states=True, return_dict=True)
logp = torch.log_softmax(out.logits[0,-1].float()/TAU, dim=-1)
token = int(torch.multinomial(logp.exp(), 1, generator=generator).item())
actions.append(token); log_old.append(float(logp[token])); old_value.append(float(head(out.hidden_states[-1][0,-1].float())))
old_entropy.append(float(-(logp.exp()*logp).sum()))
if token in EOS: break
verify, _, _ = stats(model,head,prefix,actions)
old = torch.tensor(log_old, device='cuda')
if not torch.allclose(verify, old, atol=2e-4, rtol=2e-4):
raise RuntimeError('Las log-probs del muestreo y la evaluación no coinciden')
ref, _, _ = stats(model,head,prefix,actions,reference=True)
if not torch.isfinite(old).all() or not torch.isfinite(ref).all():
raise ValueError('Log-probabilidades no finitas en el rollout')
return {'prompt_id':item['prompt_id'], 'prompt':item['prompt'], 'prefix':prefix, 'actions':actions,
'text':tok.decode(actions, skip_special_tokens=True), 'old_logp':log_old,
'ref_logp':ref.tolist(), 'old_values':old_value, 'old_entropy':old_entropy,
'ended_eos':actions[-1] in EOS, 'truncated':actions[-1] not in EOS}
class SentimentReward:
def __init__(self):
self.tok = AutoTokenizer.from_pretrained(SENTIMENT, revision=SENTIMENT_REV, local_files_only=OFFLINE)
self.model = AutoModelForSequenceClassification.from_pretrained(SENTIMENT, revision=SENTIMENT_REV,
local_files_only=OFFLINE, dtype=torch.float32).to('cuda').eval()
labels = {str(v).upper():int(k) for k,v in self.model.config.id2label.items()}
if 'POSITIVE' not in labels: raise ValueError('No se ha identificado la clase positiva')
self.positive = labels['POSITIVE']
snapshot = snapshot_download(SENTIMENT, revision=SENTIMENT_REV, local_files_only=OFFLINE,
allow_patterns=['*.safetensors'])
weights = hashes(snapshot)
if not weights: raise ValueError('No se encontraron pesos safetensors del clasificador')
self.metadata = {'kind':'clasificador sentimiento', 'model':SENTIMENT, 'revision':SENTIMENT_REV,
'weights_sha256':weights, 'score':'probabilidad clase positiva',
'input':'continuación decodificada; máximo 512 tokens del clasificador'}
def __call__(self, row):
full_ids = self.tok(row['text'], truncation=False)['input_ids']
row['classifier_tokens_before_truncation'] = len(full_ids)
row['classifier_truncated'] = len(full_ids) > 512
batch = self.tok(row['text'], return_tensors='pt', truncation=True, max_length=512).to('cuda')
with torch.no_grad(): return float(self.model(**batch).logits.softmax(-1)[0,self.positive])
class PairReward:
def __init__(self, directory):
directory = Path(directory)
meta = json.loads((directory/'reward-meta.json').read_text(encoding='utf-8'))
self.tok = AutoTokenizer.from_pretrained(directory/meta['adapter'], local_files_only=True)
base = AutoModel.from_pretrained(meta['model'], revision=meta['revision'], local_files_only=OFFLINE,
dtype=torch.float32, attn_implementation='sdpa').to('cuda')
snapshot = snapshot_download(meta['model'], revision=meta['revision'], local_files_only=OFFLINE,
allow_patterns=['*.safetensors'])
if hashes(snapshot) != meta['weights_sha256']:
raise ValueError('Las huellas de la base reward no coinciden')
self.model = PeftModel.from_pretrained(base, directory/meta['adapter'], is_trainable=False).eval()
self.head = torch.nn.Linear(meta['hidden_size'],1,bias=False,device='cuda')
self.head.load_state_dict(load_file(str(directory/meta['head_file']), device='cpu')); self.head.eval()
self.max_context = meta['max_context']
if file_hash(directory/meta['head_file']) != meta['head_sha256']:
raise ValueError('La huella de la cabeza reward no coincide')
if file_hash(directory/meta['adapter']/'adapter_model.safetensors') != meta['adapter_sha256']:
raise ValueError('La huella del adaptador reward no coincide')
self.metadata = {'kind':'reward model l18', 'model':meta['model'], 'revision':meta['revision'],
'head_sha256':meta['head_sha256'], 'adapter_sha256':meta['adapter_sha256'],
'metadata_sha256':file_hash(directory/'reward-meta.json'),
'base_weights_sha256':meta['weights_sha256']}
def __call__(self, row):
if any(t and t in row['prompt']+row['text'] for t in self.tok.all_special_tokens):
raise ValueError('El contenido incluye una grafía de token especial del reward model')
messages = [{'role':'user','content':row['prompt']},{'role':'assistant','content':row['text']}]
ids = self.tok.apply_chat_template(messages, tokenize=True, add_generation_prompt=False)
if isinstance(ids, Mapping): ids = ids['input_ids']
if not ids or len(ids)>self.max_context: raise ValueError('Respuesta fuera de contexto del reward model')
t = torch.tensor([ids],device='cuda')
with torch.no_grad():
hidden = self.model(input_ids=t, attention_mask=torch.ones_like(t), use_cache=False,
return_dict=True).last_hidden_state[0,-1]
return float(self.head(hidden.float()).squeeze())
def checkpoint(model, head, step, manifest):
path = OUT/f'checkpoint-{step}'
model.save_pretrained(path, safe_serialization=True)
save_file({'weight':head.weight.detach().cpu().contiguous(), 'bias':head.bias.detach().cpu().contiguous()},
str(path/'value-head.safetensors'))
data = {**manifest, 'step':step, 'adapter_sha256':file_hash(path/'adapter_model.safetensors'),
'value_head_sha256':file_hash(path/'value-head.safetensors')}
(path/'manifest.json').write_text(json.dumps(data,ensure_ascii=False,indent=2),encoding='utf-8')
def main():
if not torch.cuda.is_available(): raise RuntimeError('Este laboratorio requiere CUDA')
meta_path = SFT/'sft-report.json'; base_dir = SFT/'final'
if not meta_path.is_file() or not base_dir.is_dir(): raise FileNotFoundError('Ejecuta y guarda el SFT de l15 primero')
sft_report = json.loads(meta_path.read_text(encoding='utf-8'))
if not sft_report.get('checkpoint_saved'): raise ValueError('El SFT no guardó checkpoint')
if sft_report.get('model') != 'HuggingFaceTB/SmolLM2-135M': raise ValueError('Se esperaba el SFT SmolLM2 de l15')
base_hashes = hashes(base_dir)
if not base_hashes: raise ValueError('No hay pesos safetensors en el checkpoint SFT')
OUT.mkdir(parents=True, exist_ok=True)
random.seed(SEED); np.random.seed(SEED); torch.manual_seed(SEED); torch.cuda.manual_seed_all(SEED)
tok = AutoTokenizer.from_pretrained(base_dir, local_files_only=True)
base = AutoModelForCausalLM.from_pretrained(base_dir, local_files_only=True, dtype=torch.float32,
attn_implementation='sdpa').to('cuda')
base.config.use_cache = False
config = LoraConfig(r=8, lora_alpha=16, lora_dropout=0., bias='none', task_type='CAUSAL_LM',
target_modules=['q_proj','v_proj'])
model = get_peft_model(base,config).eval()
named_trainable = [(name,p) for name,p in model.named_parameters() if p.requires_grad]
if not named_trainable or any('lora_' not in name for name,_ in named_trainable):
raise RuntimeError('La política tiene pesos entrenables fuera de LoRA')
trainable = [p for _,p in named_trainable]
head = torch.nn.Linear(model.config.hidden_size,1,device='cuda',dtype=torch.float32)
optimizer = torch.optim.AdamW([{'params':trainable,'lr':1e-5},{'params':head.parameters(),'lr':1e-4}])
reward = PairReward(REWARD_DIR) if REWARD_DIR else SentimentReward()
cases = prompts(); generator = torch.Generator(device='cuda').manual_seed(SEED)
beta = BETA; logs = []
manifest = {'seed':SEED, 'sft_dir':str(SFT), 'sft_report_sha256':file_hash(meta_path),
'sft_weights_sha256':base_hashes, 'reference':'base SFT exacta con adaptador PPO desactivado',
'reward':reward.metadata, 'template':'SmolLM2 SFT l15, user y prefijo assistant',
'sampling':{'temperature':TAU, 'top_k':None, 'top_p':None, 'eos_ids':list(EOS),
'max_new_tokens':MAX_NEW, 'no_eos_penalty':NO_EOS_PENALTY,
'truncation':'horizonte finito terminal, sin bootstrap'},
'beta_initial':BETA, 'adaptive_kl':ADAPT_KL, 'kl_target_per_sequence':KL_TARGET,
'kl_horizon_sequences':KL_HORIZON, 'gamma':GAMMA, 'lambda':LAMBDA, 'clip':CLIP}
checkpoint(model,head,0,manifest)
fixed_probe = None; reference_before = None
for step in range(UPDATES):
rows = [rollout(model,head,tok,cases[(step*ROLLOUTS+i)%len(cases)],generator) for i in range(ROLLOUTS)]
if step == 0 and any(not np.allclose(r['old_logp'],r['ref_logp'],atol=2e-4,rtol=2e-4) for r in rows):
raise RuntimeError('El adaptador inicial no reproduce la referencia SFT')
if fixed_probe is None:
fixed_probe = (rows[0]['prefix'], rows[0]['actions'])
reference_before = reference_probe(model, *fixed_probe)
for row in rows:
row['terminal_reward'] = reward(row)
if not math.isfinite(row['terminal_reward']): raise ValueError('Recompensa terminal no finita')
kl = np.asarray(row['old_logp'])-np.asarray(row['ref_logp'])
per_token = -beta*kl; per_token[-1] += row['terminal_reward'] - (NO_EOS_PENALTY if row['truncated'] else 0.)
values = np.asarray(row['old_values'])
advantages, returns = gae(per_token[None,:],values[None,:],np.ones((1,len(values)),bool),GAMMA,LAMBDA)
row.update({'token_rewards':per_token.tolist(), 'advantages':advantages[0].tolist(),
'returns':returns[0].tolist(), 'sampled_kl':float(kl.sum())})
flat = np.concatenate([np.asarray(r['advantages']) for r in rows])
mean, std = float(flat.mean()), float(flat.std())
for row in rows:
row['normalized_advantages'] = ((np.asarray(row['advantages'])-mean)/(std+1e-8)).tolist() if len(flat)>1 and std>1e-8 else row['advantages']
for _ in range(EPOCHS):
optimizer.zero_grad(set_to_none=True); total = sum(len(r['actions']) for r in rows)
for row in rows:
lp, value, entropy = stats(model,head,row['prefix'],row['actions'])
old = torch.tensor(row['old_logp'],device='cuda'); adv = torch.tensor(row['normalized_advantages'],device='cuda')
target = torch.tensor(row['returns'],device='cuda'); ratio = torch.exp(lp-old)
if not torch.isfinite(ratio).all() or not torch.isfinite(value).all():
raise ValueError('Razones PPO o valores no finitos')
policy = -torch.minimum(ratio*adv, ratio.clamp(1-CLIP,1+CLIP)*adv).sum()/total
value_loss = .5*(value-target).square().sum()/total
(policy + .5*value_loss).backward()
torch.nn.utils.clip_grad_norm_(trainable+list(head.parameters()),1.)
optimizer.step()
reference_after = reference_probe(model, *fixed_probe)
reference_change = float((reference_after-reference_before).abs().max())
if not torch.allclose(reference_after,reference_before,atol=2e-5,rtol=2e-5):
raise RuntimeError('La distribución de la referencia SFT cambió tras la actualización')
kl_mean = sum(r['sampled_kl'] for r in rows)/len(rows)
logs.append({'step':step+1,'beta':beta,'mean_sampled_sequence_kl':kl_mean,
'mean_terminal_reward':sum(r['terminal_reward'] for r in rows)/len(rows),
'mean_length':sum(len(r['actions']) for r in rows)/len(rows),
'mean_entropy_per_token':sum(sum(r['old_entropy']) for r in rows)/sum(len(r['actions']) for r in rows),
'reference_max_logprob_change':reference_change,
'rollouts':rows})
checkpoint(model,head,step+1,{**manifest,'beta_at_rollout':beta})
if ADAPT_KL:
error = max(-.2,min(.2,kl_mean/KL_TARGET-1.))
beta *= 1 + error * min(1.,len(rows)/KL_HORIZON)
logs[-1]['beta_next'] = beta
(OUT/'ppo-report.json').write_text(json.dumps({'manifest':manifest,'updates':logs},ensure_ascii=False,indent=2),encoding='utf-8')
print('Paso:',step+1,'recompensa:',logs[-1]['mean_terminal_reward'],'KL muestral:',kl_mean,flush=True)
del reward, model, head, optimizer; gc.collect(); torch.cuda.empty_cache()
if __name__ == '__main__': main()npm run lab and open the connection link.Optimizing the proxy is not optimizing the goal
Reward overoptimization occurs when continuing to improve the evaluator used for training worsens another measure of interest. It is an empirical possibility, not a law that must appear in every run. Gao and colleagues studied PPO and best-of-N in a setting where a larger reward model served as reference for a smaller one. That “gold” model was another automated approximation, not human judgment or perfect truth.
The authors fitted forms for reference score as a function of : for best-of-N, , and for RL, , under the studied conditions and normalization. These are empirical fits, not universal identities; in particular the second expression should not be extrapolated carelessly near zero. They proposed the best-of-N form with data up to and later checked it in an experiment up to . The reference evaluator had 6 billion parameters; synthetic labels were formed by ordering its own scores. Before comparing a new curve, check which policy is the reference, how KL is measured, and whether scores use the same normalization.
Both panels include a real QUICK-mode lab report: two held-out prompts, one seed and one PPO update. Its results verify the flow and do not establish a general curve or demonstrate overoptimization. The report SHA-256 is 528b384d221d34d25d57328dd96d66937e999227e62329d5f142cfc670f9f293. Scores come from automatic models and the judge is not human truth.
Reward hacking includes exploiting evaluator regularities that do not reflect intent: unnecessary length, flattery or repeated format can correlate with high scores without improving the answer. None of these patterns alone proves exploitation; inspect the prompt, response, external criteria and counterexamples. The following viewer shows outputs retained from that short test.
Automatic judge, proxies and overoptimization
First run stage train, which asks Qwen2.5-3B-Instruct for an ordinal score for both texts in each pair. Train a Smol proxy and two Qwen proxies of equal architecture and seeds with nested budgets: one receives the first half of available pairs and the other all pairs. Both Qwen models retain the same validation and number of updates; the report records how many pairs were available and actually used. In QUICK, four steps cover a tiny sample and cannot establish a data-size effect. By default pairs come from the public UltraFeedback corpus; if a local JSONL is specified its fingerprint is recorded without verifying provenance. Labels come from an automatic model, not human preferences; validation comparisons and test prompts are split by exact fingerprint. Absence of paraphrases or prior contamination is not demonstrated. Labels are regenerated with the judge; pairs are not SFT policy rollouts.
Configure ORYON_SFT_DIR, ORYON_REWARD_DIR and ORYON_OVEROPT_DIR. After train, run the PPO lab with ORYON_PPO_PROMPTS pointing to ppo-prompts.jsonl and ORYON_REWARD_DIR to one generated proxy. Repeat for the desired proxies and β values, each run in its own directory. Then run this cell with ORYON_OVEROPT_STAGE=evaluate and ORYON_PPO_DIRS containing PPO directories separated by the system path separator. The evaluator checks SFT checkpoint and proxy fingerprints in each manifest. Models load in stages to limit memory. ORYON_QUICK=1 reduces the sample and ORYON_OFFLINE=1 requires weights and data to be available already.
The policy is sampled with full softmax at temperature one and the same finite horizon as PPO checkpoints; the sequence log-probability ratio is estimated from that sampling. Each run is reported separately. A negative Monte Carlo estimate has no real square root and is omitted from the graph. For best-of-N the square root of the KL upper bound is shown, not measured KL. The judge returns a mean of digits 0 through 4 with restricted logits: it is a judge signal, not a probability of correctness or a human arbiter. Output saves rollouts and report and does not assume a decline. Inspect texts before sharing them.
"""Preferencias del juez, proxies distintos y evaluación best-of-N y PPO.
La primera ejecución entrena los proxies. La segunda evalúa los checkpoints PPO
producidos por la celda PPO de la lección. El juez es un modelo, no verdad humana.
"""
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, 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'
MODE = os.getenv('ORYON_OVEROPT_STAGE', 'train')
OUT = Path(os.getenv('ORYON_OVEROPT_DIR', './oryon-overoptimization'))
SFT = Path(os.getenv('ORYON_SFT_DIR', './oryon-sft'))
REWARD = Path(os.getenv('ORYON_REWARD_DIR', './oryon-reward'))
PPO_ROOT = Path(os.getenv('ORYON_PPO_DIR', './oryon-ppo'))
PPO_ROOTS = [Path(p) for p in os.getenv('ORYON_PPO_DIRS', str(PPO_ROOT)).split(os.pathsep) if p]
LOCAL = os.getenv('ORYON_REWARD_JSONL', '')
DATA = 'HuggingFaceH4/ultrafeedback_binarized'
DATA_REV = '3949bf5f8c17c394422ccfab0c31ea9c20bdeb85'
JUDGE = 'Qwen/Qwen2.5-3B-Instruct'
JUDGE_REV = 'aa8e72537993ba99e69dfaafa59ed015b17504d1'
PROXIES = [('smol', 'HuggingFaceTB/SmolLM2-135M', '93efa2f097d58c2a74874c7e644dbc9b0cee75a2'),
('qwen-mitad', 'Qwen/Qwen2.5-0.5B-Instruct', '7ae557604adf67be50417f59c2c2f167def9a775'),
('qwen', 'Qwen/Qwen2.5-0.5B-Instruct', '7ae557604adf67be50417f59c2c2f167def9a775')]
SEED = 1919
N_TRAIN, N_VAL, N_TEST = (4, 2, 2) if QUICK else (256, 32, 16)
STEPS = 4 if QUICK else 256
N_CANDIDATES = 4 if QUICK else 16
NEW_TOKENS = 8 if QUICK else 48
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.open('rb') as f:
for chunk in iter(lambda:f.read(1048576), b''): h.update(chunk)
return h.hexdigest()
def write_json(path, value): path.write_text(json.dumps(value, ensure_ascii=False, indent=2), encoding='utf-8')
def unload(*models):
# Los objetos se liberan al salir de sus funciones y antes de la siguiente fase.
gc.collect(); torch.cuda.empty_cache()
def ids_from_chat(tok, messages, generation=False):
if any(t and t in m['content'] for m in messages for t in tok.all_special_tokens):
raise ValueError('Grafía de control en texto ordinario')
ids = tok.apply_chat_template(messages, tokenize=True, add_generation_prompt=generation)
if isinstance(ids, Mapping): ids = ids['input_ids']
if not ids: raise ValueError('Plantilla vacía')
return ids
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('En 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('Formato inesperado')
if [m.get('role') for m in a] != ['user','assistant'] or [m.get('role') for m in b] != ['user','assistant']:
raise ValueError('Roles inesperados')
q, x, y = a[0].get('content'), a[1].get('content'), b[1].get('content')
if not all(isinstance(v,str) and v.strip() for v in (q,x,y)) or q != b[0].get('content'):
raise ValueError('Par inválido')
if len(q)>300 or max(len(x),len(y))>500: raise ValueError('Texto demasiado largo')
return {'prompt':q, 'a':x, 'b':y, 'prompt_id':sha(normal(q))}
def data():
prior = json.loads((REWARD/'reward-report.json').read_text(encoding='utf-8'))
test = []
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 prior['test_prompt_hashes'] or row['split']!='test_prefs':
raise ValueError('Test no coincide con el informe previo')
if key not in {r['prompt_id'] for r in test}: test.append(row)
if len(test)==N_TEST: break
if len(test)<N_TEST: raise ValueError('Faltan prompts test')
blocked = {r['prompt_id'] for r in test}
train, val, seen = [], [], set()
for raw in source():
try: row = parse(raw)
except (ValueError, AttributeError): continue
key = row['prompt_id']
if key in blocked or key in seen: continue
seen.add(key)
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('No hay suficientes pares separados')
return train, val, test
def judge_rating(tok, model, prompt, answer):
# El juez produce un valor ordinal restringido, no probabilidad de verdad.
text = ('Rate how well the answer addresses the request from 0 to 4. '
'Reply with one digit only.\nRequest: '+prompt+'\nAnswer: '+answer)
ids = ids_from_chat(tok, [{'role':'user','content':text}], True)
if len(ids)>1024: raise ValueError('Entrada completa demasiado larga para el juez')
labels = [tok.encode(str(k),add_special_tokens=False) for k in range(5)]
if any(len(a)!=1 for a in labels) or len({a[0] for a in labels})!=5:
raise ValueError('Los cinco dígitos no son tokens distintos')
x = torch.tensor([ids],device='cuda')
logits = model(input_ids=x,use_cache=False).logits[0,-1,[a[0] for a in labels]].float()
p = logits.softmax(-1)
return float((p * torch.arange(5,device='cuda')).sum())
def judge_all(records):
if not torch.cuda.is_bf16_supported(): raise RuntimeError('El juez requiere bfloat16')
tok = AutoTokenizer.from_pretrained(JUDGE,revision=JUDGE_REV,local_files_only=OFFLINE)
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 records:
for key in ('a','b'):
row['judge_'+key] = judge_rating(tok,model,row['prompt'],row[key])
del model, tok; unload()
def proxy_input(tok, prompt, answer):
ids = ids_from_chat(tok,[{'role':'user','content':prompt},{'role':'assistant','content':answer}])
if len(ids)>384: raise ValueError('Respuesta completa no cabe en el proxy')
return torch.tensor([ids],device='cuda')
def train_proxy(name, repo, rev, train, val):
# Misma inicialización y flujo aleatorio para comparar presupuestos Qwen.
torch.manual_seed(SEED); torch.cuda.manual_seed_all(SEED)
snapshot=Path(snapshot_download(repo,revision=rev,local_files_only=OFFLINE,allow_patterns=['*.safetensors']))
base_hashes={p.name:file_hash(p) for p in sorted(snapshot.glob('*.safetensors'))}
if not base_hashes: raise ValueError('No se han encontrado pesos base safetensors')
tok = AutoTokenizer.from_pretrained(repo,revision=rev,local_files_only=OFFLINE)
if name=='smol':
if (tok.convert_tokens_to_ids('<|im_start|>'),tok.convert_tokens_to_ids('<|im_end|>'))!=(1,2):
raise ValueError('Tokenizador Smol sin los delimitadores esperados')
# Coincide con la plantilla explícita del SFT de m20-l15 y se guarda con el adaptador.
tok.chat_template=("{% for message in messages %}{{ '<|im_start|>' + message['role'] + '\\n' + "
"message['content'] + '<|im_end|>\\n' }}{% endfor %}"
"{% if add_generation_prompt %}{{ '<|im_start|>assistant\\n' }}{% endif %}")
backbone = AutoModel.from_pretrained(repo,revision=rev,dtype=torch.float32,
local_files_only=OFFLINE).to('cuda')
backbone.config.use_cache=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'])
model=get_peft_model(backbone,config)
head=torch.nn.Linear(model.config.hidden_size,1,bias=False,device='cuda')
opt=torch.optim.AdamW([p for p in model.parameters() if p.requires_grad]+list(head.parameters()),lr=1e-4)
def score(q,a):
ids=proxy_input(tok,q,a)
h=model(input_ids=ids,attention_mask=torch.ones_like(ids),use_cache=False,
return_dict=True).last_hidden_state[0,-1].float()
return head(h).squeeze()
for step in range(STEPS):
row=train[step%len(train)]; model.train(); opt.zero_grad(set_to_none=True)
a,b=score(row['prompt'],row['a']),score(row['prompt'],row['b'])
# Los empates de juez se omiten, no se convierten en preferencias.
loss=F.softplus(b-a) if row['judge_a']>row['judge_b'] else F.softplus(a-b)
loss.backward(); torch.nn.utils.clip_grad_norm_(list(model.parameters())+list(head.parameters()),1.)
opt.step()
model.eval()
with torch.inference_mode():
correct=[float((score(r['prompt'],r['a'])-score(r['prompt'],r['b'])).item()*(r['judge_a']-r['judge_b'])>0) for r in val]
path=OUT/name; path.mkdir(parents=True,exist_ok=True)
model.save_pretrained(path/'adapter',safe_serialization=True); tok.save_pretrained(path/'adapter')
save_file({'weight':head.weight.detach().cpu().contiguous()},str(path/'reward-head.safetensors'))
meta={'model':repo,'revision':rev,'hidden_size':model.config.hidden_size,'max_context':384,
'head_file':'reward-head.safetensors','adapter':'adapter','head':'linear sin sesgo',
'template':'apply_chat_template user + assistant','pooling':'último token real, sin padding',
'dtype':'float32','weights_sha256':base_hashes,
'head_sha256':file_hash(path/'reward-head.safetensors'),
'adapter_sha256':file_hash(path/'adapter'/'adapter_model.safetensors'),
'validation_pair_accuracy':sum(correct)/len(correct),'steps':STEPS,
'train_pairs_available':len(train),'train_pairs_seen':min(STEPS,len(train)),
'train_prompt_ids':[r['prompt_id'] for r in train],
'validation_prompt_ids':[r['prompt_id'] for r in val]}
write_json(path/'reward-meta.json',meta)
del opt,head,model,backbone,tok; unload()
return meta
def policy_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 política no usa la plantilla SFT esperada')
def plain(text):
if any(t and t in text for t in tok.all_special_tokens): raise ValueError('Grafía de control en el prompt')
ids=tok.encode(text,add_special_tokens=False)
if set(ids)&set(tok.all_special_ids) or tok.decode(ids,skip_special_tokens=False,clean_up_tokenization_spaces=False)!=text:
raise ValueError('El prompt no admite ida y vuelta ordinaria')
return ids
return [start]+plain('user\n')+plain(prompt)+[end]+plain('\n')+[start]+plain('assistant\n')
def rollout(model, tok, prompt, count, adapter=False):
prefix=policy_prompt(tok,prompt)
if len(prefix)+NEW_TOKENS>model.config.max_position_embeddings: raise ValueError('El prompt no cabe sin recortar')
x=torch.tensor([prefix],device='cuda'); results=[]
with torch.inference_mode():
for _ in range(count):
actions=[]
for _ in range(NEW_TOKENS):
partial=torch.tensor([prefix+actions],device='cuda')
last=model(input_ids=partial,use_cache=False).logits[0,-1].float()
token=int(torch.multinomial(last.softmax(-1),1).item())
actions.append(token)
if token in (0,2): break
seq=torch.tensor(prefix+actions,device='cuda')
answer=seq[len(prefix):]
if not len(answer): raise ValueError('La política no devolvió tokens')
content=tok.decode(answer.tolist(),skip_special_tokens=True,clean_up_tokenization_spaces=False)
# Ambas distribuciones usan softmax completo a temperatura uno.
delta=None
if adapter:
logits=model(input_ids=seq[None,:],use_cache=False).logits[0,len(prefix)-1:-1].float()
lp=logits.log_softmax(-1).gather(1,answer[:,None]).sum()
with model.disable_adapter():
ref=model(input_ids=seq[None,:],use_cache=False).logits[0,len(prefix)-1:-1].float()
lq=ref.log_softmax(-1).gather(1,answer[:,None]).sum()
delta=float(lp-lq)
if not math.isfinite(delta): raise ValueError('Cociente de log-probabilidades no finito')
results.append({'text':content,'ids':answer.tolist(),'log_ratio':delta,
'ended_with':'eos' if int(answer[-1]) in (0,2) else 'límite'})
return results
def load_policy():
path=SFT/'final'
tok=AutoTokenizer.from_pretrained(path,local_files_only=True)
model=AutoModelForCausalLM.from_pretrained(path,dtype=torch.float32,local_files_only=True).to('cuda').eval()
return model,tok
def collect_rollouts(test):
weights={p.name:file_hash(p) for p in sorted((SFT/'final').glob('*.safetensors'))}
if not weights: raise ValueError('No existen pesos SFT guardados')
model,tok=load_policy()
base=[]
for row in test:
for c in rollout(model,tok,row['prompt'],N_CANDIDATES):
base.append({'prompt':row['prompt'],'prompt_id':row['prompt_id'],'candidate':c})
del model,tok; unload()
ppo=[]
checkpoints=[p for root in PPO_ROOTS for p in sorted(root.glob('checkpoint-*'))]
for checkpoint in checkpoints:
manifest=json.loads((checkpoint/'manifest.json').read_text(encoding='utf-8'))
if manifest['sft_weights_sha256']!=weights: raise ValueError('Checkpoint PPO usa otro SFT')
sampling=manifest['sampling']
if (sampling['temperature']!=1 or sampling['top_k'] is not None or sampling['top_p'] is not None
or sampling['eos_ids']!=[0,2] or sampling['max_new_tokens']!=NEW_TOKENS):
raise ValueError('Para esta comparación PPO debe usar softmax completo a temperatura uno')
reward=manifest['reward']; matches=[]
for name,_,_ in PROXIES:
path=OUT/name
if reward.get('metadata_sha256') is not None and reward['metadata_sha256']!=file_hash(path/'reward-meta.json'):
continue
if reward.get('head_sha256')==file_hash(path/'reward-head.safetensors') and reward.get('adapter_sha256')==file_hash(path/'adapter'/'adapter_model.safetensors'):
matches.append(name)
if len(matches)!=1: raise ValueError('El checkpoint PPO no pertenece a ninguno de estos proxies')
model,tok=load_policy()
policy=PeftModel.from_pretrained(model,checkpoint).eval()
for row in test:
c=rollout(policy,tok,row['prompt'],1,adapter=True)[0]
ppo.append({'prompt':row['prompt'],'prompt_id':row['prompt_id'],'candidate':c,
'step':manifest['step'],'beta':manifest.get('beta_at_rollout') if manifest.get('beta_at_rollout') is not None else manifest['beta_initial'],
'proxy':matches[0],'training_seed':manifest['seed'],
'run_id':sha(str(checkpoint.parent.resolve()))[:12], 'checkpoint':checkpoint.name})
del policy,model,tok; unload()
if not ppo: raise ValueError('No hay checkpoints PPO: ejecuta primero el laboratorio PPO con uno de los proxies')
return base,ppo,weights
def score_proxy(name, rows):
path=OUT/name; meta=json.loads((path/'reward-meta.json').read_text(encoding='utf-8'))
tok=AutoTokenizer.from_pretrained(path/'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,path/'adapter').eval()
head=load_file(str(path/meta['head_file']),device='cpu')['weight'].to('cuda').float()
with torch.inference_mode():
for row in rows:
ids=proxy_input(tok,row['prompt'],row['candidate']['text'])
h=model(input_ids=ids,attention_mask=torch.ones_like(ids),use_cache=False,
return_dict=True).last_hidden_state[0,-1].float()
v=float((head@h).item())
if not math.isfinite(v): raise ValueError('Recompensa proxy no finita')
row.setdefault('proxy_scores',{})[name]=v
del head,model,base,tok; unload()
def score_gold(rows):
if not torch.cuda.is_bf16_supported(): raise RuntimeError('El juez requiere bfloat16')
tok=AutoTokenizer.from_pretrained(JUDGE,revision=JUDGE_REV,local_files_only=OFFLINE)
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:
row['judge']=judge_rating(tok,model,row['prompt'],row['candidate']['text'])
del model,tok; unload()
def mean(values): return sum(values)/len(values)
def standard_error(values):
if len(values)<2: return None
m=mean(values)
return math.sqrt(sum((x-m)**2 for x in values)/(len(values)*(len(values)-1)))
def summarize(base, ppo, test):
groups={r['prompt_id']:[x for x in base if x['prompt_id']==r['prompt_id']] for r in test}
points=[]; gallery=[]
ns=[1,2,4] if QUICK else [1,2,4,8,16]
for name,_,_ in PROXIES:
for n in ns:
choices=[max(groups[r['prompt_id']][:n],key=lambda x:x['proxy_scores'][name]) for r in test]
margin=[x['judge']-groups[x['prompt_id']][0]['judge'] for x in choices]
upper=math.log(n)-(n-1)/n
points.append({'method':'best_of_n','proxy':name,'beta':None,'step':None,'n':n,
'sqrt_kl':math.sqrt(upper),'kl_kind':'upper_bound',
'proxy_mean':mean([x['proxy_scores'][name] for x in choices]),'judge_margin':mean(margin)})
for name,run_id in sorted({(r['proxy'],r['run_id']) for r in ppo}):
for step,beta in sorted({(r['step'],r['beta']) for r in ppo if (r['proxy'],r['run_id'])==(name,run_id)}):
selected=[r for r in ppo if (r['proxy'],r['run_id'],r['step'],r['beta'])==(name,run_id,step,beta)]
ratios=[r['candidate']['log_ratio'] for r in selected]
kl=mean(ratios)
margin=[r['judge']-groups[r['prompt_id']][0]['judge'] for r in selected]
points.append({'method':'ppo','proxy':name,'run_id':run_id,'beta':beta,'step':step,'n':None,'kl_estimate':kl,'kl_standard_error':standard_error(ratios),
'sqrt_kl':math.sqrt(kl) if kl>=0 else None,'kl_kind':'estimate',
'proxy_mean':mean([r['proxy_scores'][name] for r in selected]),'judge_margin':mean(margin)})
for r,m in zip(selected,margin):
gallery.append({'prompt_id':r['prompt_id'],'prompt':r['prompt'],'response':r['candidate']['text'],
'baseline':groups[r['prompt_id']][0]['candidate']['text'],'step':step,'beta':beta,
'proxy':name,'proxy_score':r['proxy_scores'][name],'judge_margin':m,
'training_seed':r['training_seed'],'run_id':r['run_id'],'checkpoint':r['checkpoint'],
'ended_with':r['candidate']['ended_with']})
return points,gallery
def main():
if not torch.cuda.is_available(): raise RuntimeError('Este laboratorio requiere CUDA')
if MODE not in ('train','evaluate'): raise ValueError('ORYON_OVEROPT_STAGE debe ser train o evaluate')
OUT.mkdir(parents=True,exist_ok=True)
random.seed(SEED); np.random.seed(SEED); torch.manual_seed(SEED); torch.cuda.manual_seed_all(SEED)
if MODE=='train':
train,val,test=data(); judge_all(train+val)
train=[r for r in train if r['judge_a']!=r['judge_b']]
val=[r for r in val if r['judge_a']!=r['judge_b']]
if not train or not val: raise ValueError('El juez produjo solo empates en train o validación')
source_meta=({'kind':'jsonl local sin verificación de origen','sha256':file_hash(Path(LOCAL))} if LOCAL else
{'kind':'Hugging Face','id':DATA,'revision':DATA_REV})
write_json(OUT/'synthetic-preferences.json',{'train':train,'validation':val,'test':test,'seed':SEED,
'teacher':JUDGE,'revision':JUDGE_REV,'source':source_meta})
with (OUT/'ppo-prompts.jsonl').open('w',encoding='utf-8') as f:
for r in train: f.write(json.dumps({'prompt_id':r['prompt_id'],'prompt':r['prompt']},ensure_ascii=False)+'\n')
for name,repo,rev in PROXIES:
subset=train[:max(1,(len(train)+1)//2)] if name=='qwen-mitad' else train
print(name,train_proxy(name,repo,rev,subset,val),flush=True)
print('Proxies y prompts PPO:',OUT,flush=True)
else:
prepared=json.loads((OUT/'synthetic-preferences.json').read_text(encoding='utf-8'))
test=prepared['test']
if len(test)!=N_TEST: raise ValueError('El modo QUICK debe coincidir con el de preparación')
base,ppo,weights=collect_rollouts(test)
for name,_,_ in PROXIES: score_proxy(name,base+ppo)
score_gold(base+ppo)
points,gallery=summarize(base,ppo,test)
manifests={sha(str(p.parent.resolve()))[:12]+'/'+p.name:file_hash(p/'manifest.json')
for root in PPO_ROOTS for p in root.glob('checkpoint-*')}
report={'quick':QUICK,'seed':SEED,'points':points,'gallery':gallery,
'provenance':f'{len(test)} prompts test; una semilla; juez {JUDGE} con revisión {JUDGE_REV}.',
'protocol':{'source':prepared['source'],'teacher':JUDGE,'teacher_revision':JUDGE_REV,
'preference_file_sha256':file_hash(OUT/'synthetic-preferences.json'),
'sft_weights_sha256':weights,'checkpoint_manifest_sha256':manifests,
'temperature':1,'top_k':None,'top_p':None,'max_new_tokens':NEW_TOKENS,
'judge':'Media de 0 a 4 bajo logits restringidos a los dígitos',
'baseline':'Primer candidato SFT en el mismo prompt',
'kl':'PPO: media del cociente de log-probabilidad por secuencia; BoN: cota superior',
'tie':'primer candidato de la lista'},
'limitations':'El juez es un modelo, no verdad humana. El subconjunto es pequeño y no demuestra tendencias. La exclusión de prompts es exacta y no prueba ausencia de paráfrasis ni contaminación anterior.'}
write_json(OUT/'overoptimization-results.json',report)
write_json(OUT/'overoptimization-rollouts.json',{'base':base,'ppo':ppo})
for row in points: print(json.dumps(row,ensure_ascii=False),flush=True)
print('Informe:',OUT/'overoptimization-results.json',flush=True)
if __name__=='__main__': main()npm run lab and open the connection link.Reducing the KL budget, stopping before an evaluation drop, using ensembles or collecting new comparisons on the generated distribution are candidate mitigations, not guarantees. Reserve prompts and evaluators for selection and another split for final evaluation. If you repeatedly use the same external signal to select checkpoints, that signal also becomes part of the optimization process. An independent human audit adds another perspective and has its own protocol and disagreement.
Exercises
r = [-.02, -.03, -.01, 1.]
v = [.2, .3, .4, .5, 0.]
gae = 0.
advantages = []
for t in range(3, -1, -1):
gae = r[t] + v[t+1] - v[t] + .95 * gae
advantages.append(gae)
print('Ventajas:', list(reversed(advantages)))Step 1 of 3. How does the log probability ratio of a sequence decompose?
import numpy as np
def compute_gae(rewards, values, mask, gamma, lam):
pass
PPO turns preferences into an approximate token-level update. The reference, sampling distribution, termination and external evaluator determine what that update means and what conclusions you can draw from it.