Module contents
Lesson 5 of 31Core 110 min

Verifiers: checking is easier than solving

Study the gap between generating and verifying, exact verifiers, outcome reward models trained on sampled solutions, and generative verifiers. Quantify how imperfect verification caps best-of-N accuracy and proxy overoptimization can make extra samples hurt true outcomes.

After this lesson you can

  • Classify problems by exact, approximate, or unavailable verification and choose a selection strategy.
  • Train a LoRA outcome reward model on generated solutions labeled for correctness.
  • Derive the accuracy ceiling of best-of-N for given verifier true- and false-positive rates.
  • Calculate best-of-N policy KL divergence from the base model and relate it to overoptimization.
  • Compare voting, verifier-guided best-of-N, and weighted voting with equal sample counts.

Before you start

Check a candidate

If one of several answers is correct, you still need to recognize it. The generation–verification gap occurs when checking a proposed solution costs less than finding it: verifying a factorization by multiplying factors, for example, can be much easier than finding them. The P versus NP intuition helps frame that difference for decision problems with certificates, but does not prove that every natural answer has a short certificate or is easy to verify.

An executable verifier checks a property using symbolic computation, a solver, or tests. Specify the property: a finite test set can be exact on those cases while still accepting programs incorrect elsewhere. Symbolic simplification can depend on domain, function branches, or variable assumptions. An unsat result or checkable certificate must not be confused with proof of a specification different from the one encoded.

An outcome reward model learns to score a complete solution from correctness labels. Cobbe and colleagues trained verifiers on solutions and selected GSM8K candidates. The model may learn formatting cues or memorize problems: split training and evaluation by problem, audit labels, and measure accuracy at the score extreme actually selected, not just global AUC.

A generative verifier produces verification text and a decision using a next-token prediction objective. It can spend more compute comparing several judgments, as studied by Zhang and colleagues, but a convincing explanation does not guarantee a correct judgment. Add its tokens and latency to method cost and compare it with tests and simple baselines.

An imperfect binary verifier

Suppose each candidate is correct with probability pp and the verifier accepts a correct candidate with probability tt and an incorrect one with probability ff. Samples and decisions are independent under these constant rates. Let q=pt+(1−p)fq=pt+(1-p)f be acceptance probability. If any are accepted, choose one uniformly among them; otherwise choose uniformly among rejected candidates. With 0<q<10<q<1, accuracy is

PN=ptq[1−(1−q)N]+p(1−t)1−q(1−q)N.P_N=\frac{pt}{q}\bigl[1-(1-q)^N\bigr]+\frac{p(1-t)}{1-q}(1-q)^N.

The first ratio is the probability an accepted candidate is correct; the second is that a rejected candidate is correct. The probability of accepting none is (1−q)N(1-q)^N. The second condition matters: when none passes, candidates are conditioned on rejection and their accuracy need not be pp. If q=0q=0, none are accepted and random selection has accuracy pp; if q=1q=1, all are accepted and it is also pp.

The imperfect verifier limit appears as NN grows: if q>0q>0, accuracy converges to pt/[pt+(1−p)f]pt/[pt+(1-p)f], while coverage 1−(1−p)N1-(1-p)^N approaches one if p>0p>0. With p=0.2p=0.2, t=0.9t=0.9, and f=0.1f=0.1, the limit is 0.18/0.26≈0.69230.18/0.26\approx0.6923; coverage with 16 attempts is approximately 0.9719. This gap does not imply every selection strategy has that ceiling: it depends on the verifier, rates, and tie rule. Stroebl and colleagues analyze limits from false positives under resampling.

InteractiveThe noisy verifier ceiling
  • Selection
  • Coverage
0.20
0.90
0.10
16
Exact accuracy0.687
Simulation0.680
Limit0.692
Coverage0.972
The exact curve assumes independent candidates and decisions. When none is accepted, choose uniformly among rejected candidates; the simulation uses the same rule.

Optimize a proxy

Best-of-N overoptimization occurs when increasingly selecting by an imperfect score improves the proxy but worsens an external metric. Length bias may appear: if the scorer rewards long answers regardless of correctness, more candidates offer more opportunities to exploit that signal. Measure the curve using external labels or checkers not used for training or threshold selection.

For a continuous reward without ties, if F(r)F(r) is its cumulative distribution under base policy π\pi, the density of the policy selecting the maximum among NN samples is

dπNdπ(y)=NF(r(y))N−1,DKL(πN∥π)=log⁡N−N−1N.\frac{d\pi_N}{d\pi}(y)=N F(r(y))^{N-1},\qquad D_{\mathrm{KL}}(\pi_N\Vert\pi)=\log N-\frac{N-1}{N}.

The derivation uses that F(r(Y))F(r(Y)) is uniform under the base and its maximum has density NuN−1Nu^{N-1}. With atoms or ties, equality may fail: the expression is an upper bound under relevant assumptions, not a universal identity. Beirami and colleagues examine that distinction. Also compare actual quality against NN, not only KL; greater distance alone does not determine the direction of utility change.

InteractiveMore selection can worsen gold reward
  • Gold
  • Proxy
3.0
Horizontal axis
Gold at N=1−1.95
Gold at N=128−1.96
Continuous KL at N=1283.86
Synthetic example, not a trained ORM: for each N, the largest proxy among normal samples is selected and mean gold and proxy reported. The KL axis uses the continuous formula under this model.

Lab: noise and selection

This cell computes the binary rule and validates it by simulation. It then uses a continuous scorer: a correct candidate’s score is normal with mean 1, an incorrect one’s normal with mean 0, both with standard deviation 1. For score ss, marginal distribution F(s)F(s) mixes both populations; the probability of choosing a correct candidate is N∫pf1(s)F(s)N−1 dsN\int p f_1(s)F(s)^{N-1}\,ds. The numerical integral uses a finite interval and is approximate.

[ ]Binary verifier and continuous scoresBrowser
from math import erf, exp, log, pi, sqrt
from random import Random

def binary_exact(p, tpr, fpr, n):
    q = p*tpr + (1-p)*fpr
    if q == 0 or q == 1: return p
    none = (1-q)**n
    return p*tpr/q*(1-none) + p*(1-tpr)/(1-q)*none

def binary_sim(p, tpr, fpr, n, trials=10000):
    rng = Random(42)
    wins = 0
    for _ in range(trials):
        accepted, rejected = [], []
        for _ in range(n):
            good = rng.random() < p
            yes = rng.random() < (tpr if good else fpr)
            (accepted if yes else rejected).append(good)
        wins += rng.choice(accepted or rejected)
    return wins/trials

def normal_cdf(x): return (1+erf(x/sqrt(2)))/2
def normal_pdf(x): return exp(-x*x/2)/sqrt(2*pi)

def gaussian_exact(p, n, steps=4000):
    lo, hi = -8, 9
    dx = (hi-lo)/steps
    integral = 0
    for i in range(steps):
        s = lo+(i+.5)*dx
        F = p*normal_cdf(s-1)+(1-p)*normal_cdf(s)
        integral += n*p*normal_pdf(s-1)*F**(n-1)*dx
    return integral

def gaussian_sim(p, n, trials=10000):
    rng = Random(99)
    wins = 0
    for _ in range(trials):
        candidates = []
        for _ in range(n):
            good = rng.random() < p
            candidates.append((rng.gauss(1 if good else 0, 1), good))
        wins += max(candidates)[1]
    return wins/trials

print('Binario exacto y simulado:', binary_exact(.2,.9,.1,16), binary_sim(.2,.9,.1,16))
print('Gaussiano por integral y simulado:', gaussian_exact(.2,16), gaussian_sim(.2,16))

for n in (2, 4, 16):
    # Recompensa binaria equiprobable y desempate uniforme.
    q0 = .5**n
    q1 = 1-q0
    kl_discreta = q0*log(q0/.5)+q1*log(q1/.5)
    # Integral sobre u uniforme para la distribución continua de recompensa.
    steps = 10000
    dx = 1/steps
    kl_integral = sum((n*u**(n-1))*log(n*u**(n-1))*dx
                      for u in ((i+.5)*dx for i in range(steps)))
    cota = log(n)-(n-1)/n
    print('N',n,'KL discreta',kl_discreta,'integral continua',kl_integral,'cota',cota)

Symbolic verification with explicit scope

The following checker accepts only polynomials in xx with integer or rational coefficients and bounded length and exponent. For exponent zero it adopts the polynomial-ring convention, including the zero polynomial to the zeroth power. It does not evaluate arbitrary code. It rejects functions, additional names, and division by expressions containing variables: it does not purport to decide general equivalence or ignore points where an expression is undefined. Rejection means “out of scope,” not “mathematically different.”

[ ]Compare polynomials with SymPyLocal GPU
import ast
import sympy as sp

x = sp.Symbol('x')
def parse_polynomial(text):
    if len(text) > 120:
        raise ValueError('expresion demasiado larga')
    tree = ast.parse(text, mode='eval')
    if sum(1 for _ in ast.walk(tree)) > 50:
        raise ValueError('expresion demasiado compleja')
    def bounded(value):
        poly = sp.Poly(value,x)
        if poly.degree() > 16 or any(max(abs(int(c.p)).bit_length(), int(c.q).bit_length()) > 512 for c in poly.all_coeffs()):
            raise ValueError('grado o coeficiente excedido')
        return value
    def visit(node):
        if isinstance(node, ast.Name) and node.id == 'x': return x
        if isinstance(node, ast.Constant) and type(node.value) is int and abs(node.value) <= 10000:
            return sp.Integer(node.value)
        if isinstance(node, ast.UnaryOp) and isinstance(node.op, (ast.UAdd,ast.USub)):
            value = visit(node.operand)
            return value if isinstance(node.op,ast.UAdd) else -value
        if isinstance(node, ast.BinOp):
            left, right = visit(node.left), visit(node.right)
            if isinstance(node.op,ast.Add): return bounded(left+right)
            if isinstance(node.op,ast.Sub): return bounded(left-right)
            if isinstance(node.op,ast.Mult): return bounded(left*right)
            if isinstance(node.op,ast.Div) and right.is_Rational and right != 0: return bounded(left/right)
            if isinstance(node.op,ast.Pow) and right.is_Integer and 0 <= right <= 8:
                if right == 0: return sp.Integer(1)
                if sp.Poly(left,x).degree()*int(right) > 16: raise ValueError('grado excedido')
                return bounded(left**int(right))
        raise ValueError('formato fuera de alcance')
    result = visit(tree.body)
    if sp.Poly(result,x).degree() > 16: raise ValueError('grado excedido')
    return result

def equivalent(a,b):
    try:
        return sp.Poly(parse_polynomial(a)-parse_polynomial(b),x).is_zero
    except (ValueError, SyntaxError, sp.PolynomialError):
        return None

print('Mismo polinomio:', equivalent('(x+1)**2', 'x**2+2*x+1'))
print('Distinto:', equivalent('x+1', 'x-1'))
print('Fuera de alcance:', equivalent('x/x', '1'))
assert equivalent('0**0','1') is True and equivalent('(x-x)**2','0') is True
assert equivalent('1/(x-x)','1') is None
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Local lab: data for an outcome model

For a resumable run, download into one folder the Transformers generator, validator, v2 extractor, postprocessor, trainer, evaluator, and 2000 fixed questions. Runners log hashes and configuration and refuse to mix protocols in an output. BF16 generation with SDPA uses 16 samples per problem, batches of 256, seed 150000 + índice del primer problema del lote, and at most 256 output tokens; truncation is retained as metadata. A vLLM generator is also available, with its own seed and manifest: its results require a separate path and are not combined with the SDPA campaign.

To analyze this run’s answers without regenerating, download the 32,000 original compressed samples. The decompressed JSONL SHA256 is afa14edf14f923f6e780daf5facd925f7b7e48a1dd21e541c4afb85d99c9cde7. Decompress it and skip the first generation command; the validator and postprocessor must still be run:

python -c "import gzip,pathlib; pathlib.Path('orm_train_hf_b256.jsonl').write_bytes(gzip.decompress(pathlib.Path('orm_train_hf_b256.jsonl.gz').read_bytes()))"

To evaluate the already trained model, you can also download the LoRA adapter and manifest (SHA256 347a57e8673f68f36fd183e871c544a13dc012344181aeaeda263b2d28cec16e) and decompress it with python -m zipfile -e orm_train_run.zip .. If using it, skip the training command; retain the derived JSONL and manifest, which the evaluator checks against the adapter.

With CUDA, PyTorch, Transformers, and PEFT installed, set SNAPSHOT_15 and SNAPSHOT_05 to revisions 989aa7980e4cf806f80c7fef2b1adb7bc71aa306 and 7ae557604adf67be50417f59c2c2f167def9a775 of Qwen2.5-1.5B-Instruct and Qwen2.5-0.5B-Instruct. Also copy muestras_200x64.jsonl from lesson 3. These commands validate the corpus before training and retain checkpoints; the epoch uses batch size 8 without gradient accumulation. To resume, repeat the same command with the same files and environment:

python train_generate_fast.py --batch 256 --backend sdpa --model-path "$SNAPSHOT_15" --records gsm8k_train_2000.json --output orm_train_hf_b256.jsonl
python validate_orm_dataset.py --samples orm_train_hf_b256.jsonl --records gsm8k_train_2000.json --backend transformers --batch-problems 16
python relabel_answers_v2.py --input orm_train_hf_b256.jsonl --output orm_train_hf_b256_v2.jsonl
python train_orm_checkpoint.py --input orm_train_hf_b256_v2.jsonl --model-path "$SNAPSHOT_05" --output orm_train_run --batch 8
python score_orm_checkpoint.py --train orm_train_hf_b256_v2.jsonl --test muestras_200x64.jsonl --adapter orm_train_run/final --model-path "$SNAPSHOT_05" --output orm_scores

For subsequent selection analysis use orm_scores/orm_test_scores.jsonl. The following generation, training, and scoring cells show an alternative teaching implementation with the initial extractor; they save their own results and do not reproduce the postprocessed campaign.

The following design generates 16 solutions for each of the first 2000 GSM8K training problems: 32,000 continuations with potentially high cost. The automatic label compares extracted final answer to reference; unrecognized output remains unlabeled rather than silently becoming a failure. The explicit pattern final numerical answer was added after reviewing six pilot outputs using it. The same extractor is applied to training and test: rereading the 12,800 outputs from lesson 3 recovers 151 previously unextracted answers; 118 match the reference. This is a pilot-observed adjustment, not an independent audit, and lesson 3’s original figures retain their extractor. An assistant then reviewed 20 untruncated unextracted outputs from the first three training problems: 17 had conclusions recoverable with a conservative rule and three remained unlabeled. Version v2 preserves previous extractions and adds only an isolated LaTeX number or an explicit final-line conclusion containing one number without negation; the new rule abstains on truncation. It was fixed before applying to test and does not consult the reference. On lesson 3’s 12,800 outputs it recovers another 2101 relative to this lesson’s initial extractor, of which 1685 match the reference; 6595 remain unextracted. These rules were adjusted using examples, not independently audited, and apply equally to train and test. Test problems are not used to train or tune the verifier. The 200 test questions also do not exactly match the 2000 training questions after case and whitespace normalization; that check does not rule out paraphrases.

[ ]Generate training solutionsLocal GPU
import json, re
from decimal import Decimal, InvalidOperation
from pathlib import Path
import torch
from datasets import load_dataset
from transformers import AutoModelForCausalLM, AutoTokenizer

name = 'Qwen/Qwen2.5-1.5B-Instruct'
rev = '989aa7980e4cf806f80c7fef2b1adb7bc71aa306'
data = load_dataset('openai/gsm8k', 'main', revision='740312add88f781978c0658806c59bc2815b9866')
tokenizer = AutoTokenizer.from_pretrained(name, revision=rev)
model = AutoModelForCausalLM.from_pretrained(name, revision=rev, dtype=torch.bfloat16).to('cuda').eval()
def extraer(text):
    number = r'[+-]?(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?(?![\d,]|\.\d)'
    hits = re.findall(r'####\s*\$?\s*('+number+r')',text)
    if not hits: hits = re.findall(r'\\boxed\{\s*('+number+r')\s*\}',text)
    if not hits: hits = re.findall(r'(?i)\b(?:the\s+)?answer\s+is\s*[:$]?\s*('+number+r')',text)
    if not hits: hits = re.findall(r'(?i)\b(?:the\s+)?final\s+(?:number|answer)\s+(?:is\s*)?[:]?[\s]*\*{0,2}\$?\s*('+number+r')',text)
    if not hits: hits = re.findall(r'(?i)\b(?:the\s+)?final\s+numerical\s+answer\s+(?:is\s*)?[:]?\s*\*{0,2}\$?\s*('+number+r')',text)
    if not hits:
        m = re.fullmatch(r'\s*\$?\s*('+number+r')\s*(?:[A-Za-z%]+)?[.\s]*',text)
        hits = [m.group(1)] if m else []
    try: return str(Decimal(hits[-1].replace(',','')).normalize()) if hits else None
    except InvalidOperation: return None

path = Path('orm_train_samples.jsonl')
existing = [json.loads(s) for s in path.read_text(encoding='utf-8').splitlines()] if path.exists() else []
done = {(r['problem'],r['sample']) for r in existing}
for i in range(2000):
    row = data['train'][i]
    prompt = 'Solve step by step. '+row['question']+'\nGive the final numerical answer on its own line as #### followed by the number.'
    base = tokenizer.apply_chat_template([{'role':'user','content':prompt}], add_generation_prompt=True, return_tensors='pt')['input_ids'].to('cuda')
    for start in (0,8):
        if all((i,start+j) in done for j in range(8)): continue
        if any((i,start+j) in done for j in range(8)): raise ValueError('lote parcial; revisa el archivo')
        ids = base.repeat(8,1)
        torch.manual_seed(i*16+start)
        with torch.inference_mode():
            out = model.generate(input_ids=ids, attention_mask=torch.ones_like(ids), do_sample=True,
                temperature=.8, top_p=.9, top_k=0, repetition_penalty=1.1, max_new_tokens=256,
                pad_token_id=tokenizer.eos_token_id)
        entries = []
        for j, sequence in enumerate(out):
            text = tokenizer.decode(sequence[ids.shape[1]:],skip_special_tokens=True)
            predicted, expected = extraer(text), extraer(row['answer'])
            entries.append({'problem':i,'sample':start+j,'question':row['question'],'text':text,
                            'reference':expected,'answer':predicted,
                            'label':None if predicted is None else int(predicted==expected)})
        with path.open('a',encoding='utf-8') as f:
            for entry in entries: f.write(json.dumps(entry,ensure_ascii=False)+'\n')
        print('problema',i,'muestras',start+8,flush=True)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The next cell trains a scalar head and LoRA adapters on Qwen2.5-0.5B. It reserves problems 1800 through 1999 for validation and does not mix solutions of the same problem across splits. Labels are conditional on successful extraction, so excluded cases may be systematic. Truncating text to 768 tokens also limits evidence visible to the verifier. Retain positive and negative example counts and do not interpret training loss as test quality.

[ ]Train a verifier with LoRALocal GPU
import json, random
from pathlib import Path
import torch
from torch.utils.data import DataLoader
from transformers import AutoTokenizer, AutoModelForSequenceClassification
from peft import LoraConfig, TaskType, get_peft_model

torch.manual_seed(42); random.seed(42)
rows = [json.loads(line) for line in Path('orm_train_samples.jsonl').read_text(encoding='utf-8').splitlines()]
assert len(rows)==32000 and {(r['problem'],r['sample']) for r in rows} == {(i,j) for i in range(2000) for j in range(16)}
train = [r for r in rows if r['problem'] < 1800 and r['label'] is not None]
valid = [r for r in rows if 1800 <= r['problem'] < 2000 and r['label'] is not None]
print('Entrenamiento',len(train),'positivos',sum(r['label'] for r in train),
      'validacion',len(valid),'positivos',sum(r['label'] for r in valid),
      'sin etiqueta',sum(r['label'] is None for r in rows))
if not train or not valid or len({r['label'] for r in train}) < 2:
    raise ValueError('No hay suficientes ejemplos etiquetados de ambas clases')
name = 'Qwen/Qwen2.5-0.5B-Instruct'
rev = '7ae557604adf67be50417f59c2c2f167def9a775'
tok = AutoTokenizer.from_pretrained(name,revision=rev)
tok.pad_token = tok.eos_token
base = AutoModelForSequenceClassification.from_pretrained(name,revision=rev,num_labels=1,dtype=torch.bfloat16)
base.config.pad_token_id = tok.pad_token_id
base.config.use_cache = False
config = LoraConfig(task_type=TaskType.SEQ_CLS,r=8,lora_alpha=16,lora_dropout=.05,
                    target_modules=['q_proj','v_proj'],modules_to_save=['score'])
verificador = get_peft_model(base,config).to('cuda')

def collate(batch):
    texts = ['Question: '+r['question']+'\nSolution: '+r['text'] for r in batch]
    encoded = tok(texts,padding=True,truncation=True,max_length=768,return_tensors='pt')
    labels = torch.tensor([r['label'] for r in batch],dtype=torch.float32)
    return encoded, labels

loader = DataLoader(train,batch_size=4,shuffle=True,collate_fn=collate)
optimizer = torch.optim.AdamW((p for p in verificador.parameters() if p.requires_grad),lr=2e-4)
criterion = torch.nn.BCEWithLogitsLoss()
verificador.train()
for step,(inputs,labels) in enumerate(loader):
    inputs = {k:v.to('cuda') for k,v in inputs.items()}; labels = labels.to('cuda')
    optimizer.zero_grad(set_to_none=True)
    logits = verificador(**inputs).logits.squeeze(-1).float()
    loss = criterion(logits,labels)
    if not torch.isfinite(loss): raise ValueError('Pérdida no finita: no guardes este entrenamiento')
    loss.backward(); optimizer.step()
    if step % 100 == 0: print('lote',step,'perdida',float(loss.detach()),flush=True)
verificador.save_pretrained('orm_lora')
tok.save_pretrained('orm_lora')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Evaluate threshold and calibration on problem-level validation. For test, load the adapter without retraining or choosing the threshold there, score samples from unseen lesson 3 problems, and compare voting, highest score, and weighted voting using the same candidates and budget. Also report tokens, false positives, extraction rate, and grouped intervals from lesson 4. A final correctness label does not prove all steps in a chain are correct.

[ ]Score validation and test without mixing problemsLocal GPU
import json, re
from decimal import Decimal, InvalidOperation
from pathlib import Path
import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification
from peft import PeftModel

name = 'Qwen/Qwen2.5-0.5B-Instruct'
rev = '7ae557604adf67be50417f59c2c2f167def9a775'
tok = AutoTokenizer.from_pretrained('orm_lora'); tok.pad_token = tok.eos_token
base = AutoModelForSequenceClassification.from_pretrained(name,revision=rev,num_labels=1,dtype=torch.bfloat16)
base.config.pad_token_id = tok.pad_token_id
verificador = PeftModel.from_pretrained(base,'orm_lora').to('cuda').eval()
train_rows = [json.loads(x) for x in Path('orm_train_samples.jsonl').read_text(encoding='utf-8').splitlines()]
validation = [r for r in train_rows if 1800 <= r['problem'] < 2000 and r['label'] is not None]
test = [json.loads(x) for x in Path('muestras_200x64.jsonl').read_text(encoding='utf-8').splitlines()]
assert len({(r['problema'],r['muestra']) for r in test}) == 12800

def extraer_comun(text):
    number=r'[+-]?(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?(?![\d,]|\.\d)'
    hits=re.findall(r'####\s*\$?\s*('+number+r')',text)
    if not hits: hits=re.findall(r'\\boxed\{\s*('+number+r')\s*\}',text)
    if not hits: hits=re.findall(r'(?i)\b(?:the\s+)?answer\s+is\s*[:$]?\s*('+number+r')',text)
    if not hits: hits=re.findall(r'(?i)\b(?:the\s+)?final\s+(?:number|answer)\s+(?:is\s*)?[:]?\s*\*{0,2}\$?\s*('+number+r')',text)
    if not hits: hits=re.findall(r'(?i)\b(?:the\s+)?final\s+numerical\s+answer\s+(?:is\s*)?[:]?\s*\*{0,2}\$?\s*('+number+r')',text)
    if not hits:
        match=re.fullmatch(r'\s*\$?\s*('+number+r')\s*(?:[A-Za-z%]+)?[.\s]*',text)
        hits=[match.group(1)] if match else []
    try: return str(Decimal(hits[-1].replace(',','')).normalize()) if hits else None
    except InvalidOperation: return None

for r in test:
    r['respuesta_original'] = r['respuesta']
    r['respuesta'] = extraer_comun(r['texto'])
print('Extracciones modificadas en prueba',sum(r['respuesta']!=r['respuesta_original'] for r in test))

def score_rows(rows, question_key):
    scores, token_counts = [], []
    for start in range(0,len(rows),8):
        batch = rows[start:start+8]
        text = ['Question: '+r[question_key]+'\nSolution: '+r['text' if question_key=='question' else 'texto'] for r in batch]
        inputs = tok(text,padding=True,truncation=True,max_length=768,return_tensors='pt').to('cuda')
        with torch.inference_mode():
            logits = verificador(**inputs).logits.squeeze(-1).float()
            if not torch.isfinite(logits).all(): raise ValueError('Puntuaciones no finitas')
            values = torch.sigmoid(logits).cpu().tolist()
        scores.extend(values)
        token_counts.extend(inputs['attention_mask'].sum(dim=1).cpu().tolist())
    return scores, token_counts

valid_scores, valid_tokens = score_rows(validation,'question')
positives = [s for s,r in zip(valid_scores,validation) if r['label']==1]
negatives = [s for s,r in zip(valid_scores,validation) if r['label']==0]
if not positives or not negatives: raise ValueError('Validacion necesita ambas clases')
# Elige un umbral en validacion, maximizando TPR-FPR; desempata por el menor.
thresholds = [i/100 for i in range(101)]
def rates(threshold):
    return (sum(s>=threshold for s in positives)/len(positives),
            sum(s>=threshold for s in negatives)/len(negatives))
threshold = max(thresholds,key=lambda t:rates(t)[0]-rates(t)[1])
print('Umbral de validacion',threshold,'TPR/FPR',rates(threshold))
test_scores, test_tokens = score_rows(test,'pregunta')
scored = [{**r,'score':score,'tokens_verificador':n} for r,score,n in zip(test,test_scores,test_tokens)]
Path('orm_test_scores.jsonl').write_text(''.join(json.dumps(r,ensure_ascii=False)+'\n' for r in scored),encoding='utf-8')
known = [r for r in scored if r['respuesta'] is not None]
from sklearn.metrics import roc_auc_score
labels = [int(r['respuesta']==r['referencia']) for r in known]
if len(set(labels)) != 2: raise ValueError('La prueba conocida necesita ambas clases para AUC')
print('AUC sobre extracción conocida',roc_auc_score(labels,[r['score'] for r in known]))
tp = sum(r['score']>=threshold and r['respuesta']==r['referencia'] for r in known)
fp = sum(r['score']>=threshold and r['respuesta']!=r['referencia'] for r in known)
print('Prueba conocida',len(known),'aceptadas correctas',tp,'aceptadas incorrectas',fp,
      'sin extraccion',len(scored)-len(known))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The documented run trained the 0.5B ORM for one epoch on 15,262 labeled solutions from 1800 problems, batch size 8 and LoRA; another 200 problems and their 1633 labeled solutions were reserved for validation. Threshold 0.82 was chosen there, not on test. Of 12,800 test solutions, 6205 answers could be extracted: 4728 match the reference and 1477 do not. On those known answers AUC is 0.8764; at the chosen threshold TPR and FPR are 0.825 and 0.247. These rates exclude the 6595 unextracted outputs and do not alone measure full-system selection.

At k=64k=64, voting achieved 0.402, best ORM 0.353, and ORM-weighted voting 0.460 in this comparison; per-problem bootstrap intervals were [0.332, 0.475], [0.291, 0.413], and [0.390, 0.520], respectively. Mean cost was 20,941 generation tokens; the two rules scoring all 64 candidates added 17,897 verifier input tokens. The maximum ORM falls on an unextracted answer in an expected 0.608 proportion of problems, counting ties with uniform weight: those selections do not become correct. Thus high AUC conditional on known extraction can coexist with best-of performing worse than voting in this experiment. Lesson 4’s paired per-problem bootstrap gives best ORM minus vote [−0.111, 0.011] and weighted minus vote [0.028, 0.090]. These intervals apply to this set and resampling; they do not correct for multiple comparisons or guarantee generalization.

InteractiveORM scores on correct and incorrect solutions
01015202901ORM scoreCorrectIncorrect
0.82
View
Extracted6205/12800
TPR0.825
FPR0.247
Approximate AUC0.876
Data from 12,800 test solutions: the ROC and histogram exclude the 6595 unextracted cases; selection curves retain all. The initial threshold 0.82 was chosen on validation, and figure AUC is approximated by thresholds.

Download test scores, the validation-selected threshold, and selection summary. The decompressed JSONL SHA256 is 91277dd5bbf444533dd002c06fd629ed52fe0c131963cde1c25138df9a07fe52. To run the next cell without rescoring, decompress it as orm_test_scores.jsonl in a folder without an existing orm_scores directory.

Download the lesson 4 evaluation library into the working directory. The next comparison resamples 100 subsets per problem and size and uses its paired bootstrap to compare each rule with voting. Voting uses all candidates, including those without extraction; best ORM and weighted voting use the same positive score. Verifier cost counts tokens actually received after truncation, separately from generated tokens. Results depend on the extractor and threshold chosen on validation; they do not present a correctness signal as formal proof.

[ ]Voting and selection with the ORMLocal GPU
import json
from collections import Counter, defaultdict
from pathlib import Path
from random import Random
from statistics import mean
from evaluation import paired_bootstrap

scores_file = Path('orm_scores/orm_test_scores.jsonl')
if not scores_file.exists(): scores_file = Path('orm_test_scores.jsonl')
rows = [json.loads(x) for x in scores_file.read_text(encoding='utf8').splitlines()]
groups = defaultdict(list)
for row in rows: groups[row['problema']].append(row)
if set(groups)!=set(range(200)) or any(sorted(r['muestra'] for r in g)!=list(range(64)) for g in groups.values()):
    raise ValueError('Se requieren las 64 muestras puntuadas de cada problema')
random = Random(73)
summary = []
def choose(scores):
    maximum = max(scores.values())
    return random.choice([a for a,s in scores.items() if abs(s-maximum)<1e-12])
for k in (1,2,4,8,16,32,64):
    per_task = {'voto':[],'mejor_orm':[],'ponderado':[]}
    generated_cost, verifier_cost = [], []
    for i in range(200):
        group = groups[i]; target = group[0]['referencia']
        wins = {name:0 for name in per_task}
        for _ in range(100):
            sample = random.sample(group,k)
            counts = Counter(r['respuesta'] for r in sample)
            weights = defaultdict(float)
            for r in sample: weights[r['respuesta']] += r['score']
            top = max(r['score'] for r in sample)
            best = random.choice([r for r in sample if abs(r['score']-top)<1e-12])['respuesta']
            for name, answer in [('voto',choose(counts)),('mejor_orm',best),('ponderado',choose(weights))]:
                wins[name] += answer is not None and answer==target
            generated_cost.append(sum(r['tokens_entrada']+r['tokens_salida'] for r in sample))
            verifier_cost.append(sum(r['tokens_verificador'] for r in sample))
        for name in wins: per_task[name].append(wins[name]/100)
    for name, values in per_task.items():
        paired = paired_bootstrap([[x] for x in per_task['voto']], [[x] for x in values])
        print(k,name,'IC pareado frente a voto',paired)
        bootstrap = sorted(mean(random.choice(values) for _ in values) for _ in range(1000))
        print(k,name,'acierto',mean(values),'IC agrupado',(bootstrap[25],bootstrap[974]),
              'tokens de generación',mean(generated_cost),
              'tokens de verificación',0 if name=='voto' else mean(verifier_cost))
        summary.append({'k':k,'method':name,'accuracy':mean(values),
                        'interval_95':[bootstrap[25],bootstrap[974]],'paired_vs_vote_95':list(paired),
                        'generation_tokens':mean(generated_cost),
                        'verification_tokens':0 if name=='voto' else mean(verifier_cost)})
Path('orm_selection_summary.json').write_text(json.dumps(summary,ensure_ascii=False,indent=2),encoding='utf8')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Verify code with held-out tests

From sanitized MBPP, 25 tasks were selected and 25 variants constructed that always return the first published example’s answer. An assistant reviewed the 25 reference implementations and 25 variants on those examples; these are not human annotations or certifications of correctness across the domain. The second example is a hidden test for the variant and the third an additional contrast. Deliberate selection guarantees some output differs from the first example, so these 50 cases do not represent a model’s errors.

In this run the held-out test accepts all 25 references and two defective variants: two false positives among 25 defective variants, or 2/27 among accepted cases. The third example detects both: task 62 memorizes 1 although another minimum is 45, and task 68 always returns true although a sequence is not monotonic. A test can be exact on one input and still insufficient for the full specification. Do not run arbitrary model code in this process: the cell accepts and runs only the 25 inspected functions using syntax checks and a limited set of names; those checks are not general isolation.

[ ]Hidden tests on 50 MBPP casesLocal GPU
"""MBPP sanitized: 25 referencias y 25 variantes que memorizan un ejemplo.

Solo se ejecutan las funciones concretas inspeccionadas a continuación; no es
un ejecutor de programas arbitrarios ni un sandbox. El primer test se revela
para construir cada variante, el segundo se reserva para el verificador y el
tercero como contraste adicional.
"""
import ast, json
from datasets import load_dataset

REV = '4bb6404fdc6cacfda99d4ac4205087b89d32030c'
IDS = [11,12,14,17,19,59,62,63,67,68,72,75,77,80,84,86,90,91,93,95,96,105,106,119,120]
data = load_dataset('google-research-datasets/mbpp','sanitized',revision=REV,split='test')
rows = {row['task_id']:row for row in data if row['task_id'] in IDS}
assert set(rows)==set(IDS)
safe_names = ['len','range','sum','max','min','abs','sorted','int','str','float','list','tuple','set','enumerate','zip','all','any','round','reversed','isinstance','bool']
safe = {name:getattr(__import__('builtins'),name) for name in safe_names}
results = []
for task_id in IDS:
    row = rows[task_id]
    tree = ast.parse(row['code'])
    assert len(tree.body)==1 and isinstance(tree.body[0],ast.FunctionDef)
    name = tree.body[0].name
    forbidden = (ast.Import,ast.ImportFrom,ast.While,ast.ClassDef,ast.With,ast.Try,
                 ast.Lambda,ast.Global,ast.Nonlocal,ast.Attribute,ast.Delete,ast.Yield)
    assert not any(isinstance(n,forbidden) for n in ast.walk(tree))
    assert not any(isinstance(n,ast.Name) and n.id.startswith('__') for n in ast.walk(tree))
    assert not any(isinstance(n,ast.Call) and (not isinstance(n.func,ast.Name) or n.func.id not in safe_names+[name]) for n in ast.walk(tree))
    tests = [ast.parse(x).body[0] for x in row['test_list'][:3]]
    assert all(isinstance(t,ast.Assert) and isinstance(t.test,ast.Compare) and len(t.test.ops)==1
               and isinstance(t.test.ops[0],ast.Eq) and isinstance(t.test.left,ast.Call)
               and isinstance(t.test.left.func,ast.Name) and t.test.left.func.id==name for t in tests)
    # Los argumentos y resultados de estas 25 tareas son literales, no código.
    arguments = [[ast.literal_eval(x) for x in t.test.left.args] for t in tests]
    expected = [ast.literal_eval(t.test.comparators[0]) for t in tests]
    assert any(v!=expected[0] for v in expected[1:])
    env = {'__builtins__':safe}
    exec(compile(tree,'<reference>','exec'),env)
    function = env[name]
    observed = [function(*args) for args in arguments]
    assert observed==expected, (task_id,observed,expected)
    for variant,answers in [('referencia',observed),('memoriza_publico',[expected[0]]*3)]:
        # El verificador usa solo el segundo ejemplo, oculto a la variante.
        # El tercero queda para una comprobación adicional independiente.
        passed = answers[1] == expected[1]
        # Clasificación del asistente tras leer las 25 especificaciones y el
        # código: referencia válida en los casos revisados; memorizar una
        # respuesta constante contradice al menos otra entrada publicada.
        # No es una anotación humana ni certifica el dominio completo.
        reviewed = variant == 'referencia'
        results.append({'task_id':task_id,'variant':variant,'public':answers[0]==expected[0],
                        'hidden_pass':passed,'third_pass':answers[2]==expected[2],
                        'reviewed_on_examples':reviewed,
                        'expected':expected,'observed':answers})
accepted = [r for r in results if r['hidden_pass']]
false_positive = [r for r in accepted if not r['reviewed_on_examples']]
print('casos',len(results),'aceptados',len(accepted),'falsos positivos',len(false_positive))
print('referencias aprobadas',sum(r['hidden_pass'] for r in results if r['variant']=='referencia'))
print('variantes aprobadas',sum(r['hidden_pass'] for r in results if r['variant']=='memoriza_publico'))
print('falsos positivos detectados por el tercer ejemplo',sum(not r['third_pass'] for r in false_positive))
with open('mbpp_audit.json','w',encoding='utf8') as f: json.dump(results,f,ensure_ascii=False,indent=2)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

ProofThe Bayes limit
Prove: Each candidate is correct with probability p; the verifier accepts with TPR t and FPR f. Choose uniformly among accepted candidates.
0
Assume independence and q = pt + (1−p)f > 0.

Step 1 of 2. What is the probability that an accepted candidate is correct?

ProofKL with continuous reward
Prove: For N independent samples and continuous reward, prove KL(π_N || π) = log N − (N−1)/N.
0
Use u = F(r(y)), uniform under π, and the maximum of N uniforms.

Step 1 of 2. What is the selected u density?

Numeric
With p=0.2, TPR=0.9, and FPR=0.1, what is the accuracy limit when choosing uniformly among accepted candidates?
Code
Implement weighted_vote(answers, scores): sum non-negative scores per answer and return the one with greatest sum. In a tie choose the first answer seen. Reject empty lists, unequal lengths, and negative scores.
def weighted_vote(answers, scores):
  pass
Shift+Enter to run
Quiz
Where is it reasonable to expect a large generation–verification gap?
Key idea
More candidates expand coverage; an imperfect verifier can limit or even degrade selection.