Step-by-step verification: process reward models
Compare process and outcome supervision: stepwise reward models can prune incorrect paths before the final answer. Generate step labels with Monte Carlo rollouts, interpret them as completion-policy values, and compare ways to aggregate step scores.
After this lesson you can
- Contrast process and outcome supervision and explain how the former enables stepwise search.
- Generate step labels from Monte Carlo rollouts and quantify their binomial noise.
- Interpret Monte Carlo labels as estimates of the completion policy's Q value and derive the implications.
- Implement and compare minimum, product, last-step, and mean score aggregation for solution selection.
- Train a small PRM and evaluate it against an ORM in best-of-N selection and first-error detection.
Before you start
A correct answer does not certify the path
A solution states and then subtracts one for an incorrect reason, reaching 12. An outcome reward model (ORM) that observes only the final answer may reward it. In another solution the first three calculations are correct and the fourth fails: the final label does not say where the error arose. If a search has generated only the second step, an evaluator requiring the complete answer cannot yet distinguish that prefix from another.
A process reward model (PRM) assigns a score to each step or prefix of a solution. The score can locate an error or guide search before completing the path. There is no universal interpretation of that score: it depends on the label, displayed context, and training objective. In particular, the probability of successfully completing a prefix need not equal the probability that its last step is correct.
Two studies with different setups illustrate the distinction. Uesato and colleagues compared process and outcome supervision on GSM8K: pure outcome supervision achieved similar answer error rates with fewer labels, but improving correct reasoning required process supervision or a model emulating it. Lightman and colleagues found advantages for process supervision in their MATH setup and published PRM800K with 800,000 human step labels. Neither comparison proves every PRM outperforms every ORM: tasks, data, scales, and metrics differ.
Decide what a step is before scoring
Step segmentation turns a text sequence into evaluation units. A line, sentence, and arithmetic operation are not equivalent units. Two operations on one line force one label on both; splitting a sentence midway may produce a meaningless fragment. Segmentation also changes search depth and branching, and thus cost.
To align training and use, fix a deterministic rule in advance: for example, split on nonempty lines and retain each prefix’s score and index. Save the original string, delimiters, truncation, and rule version. An empty line should not create a scorable step. If the model uses different paragraphs when requesting completions, changing the rule only during evaluation causes distribution shift. A missing delimiter can make an entire solution one step: measure that rate rather than ignoring it.
Monte Carlo labels: future success, not local correctness
Monte Carlo step labels freeze the prefix after a step and request independent continuations from completion policy . A final-answer verifier assigns if continuation ends correctly and otherwise. The soft label is ; the hard label is . Math-Shepherd studies this kind of automatic supervision for selection and reinforcement.
If the verifier is exact and continuations are independent with the same success probability , then and . The hard label estimates another quantity: . For example, with and this probability is approximately 0.900, even though value is only 0.25. A positive hard label does not certify the step: one lucky continuation or a correct answer after erroneous reasoning suffices.
The Wilson interval describes binomial uncertainty under the assumptions above. It does not include extractor errors or dependence between samples. If an output does not permit answer extraction, automatically classifying it as incorrect changes the estimand; record abstention and its frequency. A narrow interval does not remove bias from a defective verifier.
With eight continuations there are only nine possible mean values, from to . Two prefixes with the same count may have different true values, and the hard label loses even more information: one and eight successes receive the same positive class. If samples share a systematic bias or defective template, nominal continuation count also exaggerates independent information. The seed makes the procedure repeatable but does not prove statistical independence or prevent shared model errors.
Consider a prefix with three successes, two recognized failures, and three answers the extractor cannot understand. The fraction among five recognized answers is ; assigning zero to the three abstentions yields . Neither figure is automatically the true success probability: the first assumes recognizable answers represent the others, and the second treats unknowns as failures. Report both rates or analyze sensitivity, record the denominator, and review an abstention sample. A classifier trained on the first learns success conditional on extraction, not a human step-correctness label.
A weak policy can fail a hard continuation even when the step is valid; another can recover the result after an erroneous step. Comparing absolute values between steps and policies therefore requires care. Difference measures progress relative to the mean continuation from the preceding state. Setlur and colleagues propose measuring progress with a separate prover policy and relate this difference to step advantage; this does not imply every positive difference is logical proof of correctness.
Train and use a PRM
In a causal model each prefix can be represented by the last token’s hidden state in the step, followed by a scalar head. For soft labels, binary cross-entropy accepts targets in ; with hard labels it is interpreted as binary classification. The selected token must belong to the step, not padding. If truncating, record excluded prefixes: otherwise the head may score a different token from the intended one.
For prediction and successes in recognized continuations, the soft-label loss is . It is the mean of individual Bernoulli losses for that prefix. If some prefixes have fewer recognized continuations than others, averaging one loss per prefix and one loss per continuation are different objectives: the latter gives greater weight to prefixes with more observations. Choose and report weighting. Nor does it turn an unrecognized continuation into a failure merely because its label is missing.
Split by problem before generating solutions and prefixes. Dividing lines from the same question between train and test leaks the prompt and potentially near-identical solutions. Many lines of one solution are not independent observations either: intervals should resample whole problems. With imbalanced classes compare prevalence, calibration, and per-class performance; high accuracy can be obtained by always predicting the majority class.
To check calibration, group prefixes by score interval and compare mean prediction with observed frequency of the specific target. Mean value 0.7 should correspond approximately to seven successes per ten continuations in a sufficiently large comparable group. Group uncertainty depends on problem count, not just prefix count. Acceptable calibration on sampled solutions does not guarantee calibration after iteratively selecting highest-scoring prefixes: search concentrates extreme cases that can exploit model errors.
When human step labels are available, specify the question the annotator answered: local validity, progress toward a solution, or correctness of the complete solution. Retain “I do not know” and disagreements; adjudication or measuring inter-annotator agreement reveals information hidden by a single label. Evaluation with human annotations from another problem set can be a useful external contrast, but is not equivalent to annotating your own experiment’s generations.
First-error localization requires an additional decision. Always taking the lowest-scored step produces an index even for a fully correct solution. Detecting absence of error also requires a threshold rule chosen without looking at test, and measurement of false positives on correct solutions. If the goal is only to identify the index among solutions already containing an error, the denominator must exclude the others and the result does not measure error detection. The lab evaluation declares this limitation and separates the two questions.
A PRM can degenerate into an ORM if it learns to focus mainly on the final answer. Zhang and colleagues observed limitations of Monte Carlo labels and best-of-N evaluation biases: a correct answer can contain incorrect steps and some PRMs concentrate their minimum on the final answer. Measure both answer selection and first-incorrect-step identification in an independent evaluation with process labels.
Four aggregation methods
Step score aggregation transforms into a score for ranking solutions. The minimum examines the bottleneck; the mean dilutes one bad step among many trivial ones; the last can ignore earlier errors; the product decreases as factors below one are added. If each is a calibrated conditional probability that step is correct given all preceding steps correct, the chain rule gives . Independence is unnecessary, but that condition and calibration are required. Monte Carlo future-success values do not automatically have that interpretation.
Summing logarithms prevents numerical underflow of the product but does not remove its length penalty. Mean logarithm or the -th root changes the objective: it is no longer joint probability. Choose the rule on separate validation and show results by length; do not optimize on test.
An example shows disagreement without assuming scores are joint probabilities. For A with , the minimum is 0.40 and mean 0.8125; for B with four scores of 0.70, both values are 0.70. Minimum chooses B and mean chooses A. The appropriate decision depends on whether one suspicious step should discard a solution and how scores were calibrated. No aggregator is universally better merely because it produces numbers between zero and one.
Lab: noisy labels in a controlled task
The following environment knows the first error by construction. Each solution sums four integer increments; the goal is to add four ones. The generator stochastically makes sign errors. Features available to the model are cumulative progress and length, not the true label. A simulated completer from each prefix produces eight continuations; its probability of recovering the answer depends on current state. This is a controlled check and does not replace the language-model campaign or human evaluation.
import random
from collections import Counter
import numpy as np
from sklearn.linear_model import LogisticRegression
r = random.Random(23)
def make_solution():
increments = [1 if r.random() < .75 else -1 for _ in range(4)]
prefixes = [sum(increments[:i]) for i in range(1,5)]
first_error = next((i for i,x in enumerate(increments) if x != 1), None)
return prefixes, first_error
def rollout(prefix, remaining):
# Solo permite +1 o -1: tras un -1 ya no se puede recuperar el objetivo.
return prefix + sum(1 if r.random() < .75 else -1 for _ in range(remaining)) == 4
def features(prefix, length):
return [prefix, length, prefix-length]
train_x, train_y, orm_x, orm_y, test_groups = [], [], [], [], []
for problem in range(240):
group = []
for candidate in range(8):
prefixes, first_error = make_solution()
gold = int(prefixes[-1] == 4)
if problem < 180:
orm_x.append(features(prefixes[-1],4)); orm_y.append(gold)
scores = []
for i, prefix in enumerate(prefixes):
hits = sum(rollout(prefix, 3-i) for _ in range(8))
scores.append(hits/8)
if problem < 180:
# Repetir las ocho etiquetas conserva su contribución conjunta
# a la entropía cruzada con objetivo blando hits/8.
for _ in range(hits):
train_x.append(features(prefix,i+1)); train_y.append(1)
for _ in range(8-hits):
train_x.append(features(prefix,i+1)); train_y.append(0)
group.append((prefixes,first_error,gold))
if problem >= 180: test_groups.append(group)
model = LogisticRegression(max_iter=300, random_state=23).fit(train_x,train_y)
orm = LogisticRegression(max_iter=300, random_state=23).fit(orm_x,orm_y)
selected = {name:0 for name in ('minimo','producto','ultimo','media','orm','voto')}
oracle, first_hits, first_total = 0, 0, 0
for group in test_groups:
candidates = []
for prefixes, first_error, gold in group:
probs = model.predict_proba([features(v,i+1) for i,v in enumerate(prefixes)])[:,1]
score = {'minimo':min(probs), 'producto':float(np.prod(probs)),
'ultimo':probs[-1], 'media':float(np.mean(probs)),
'orm':orm.predict_proba([features(prefixes[-1],4)])[0,1]}
candidates.append((score,gold,prefixes[-1]))
if first_error is not None:
first_hits += int(int(np.argmin(probs)) == first_error)
first_total += 1
for method in ('minimo','producto','ultimo','media','orm'):
selected[method] += max(candidates,key=lambda row:row[0][method])[1]
counts = Counter(row[2] for row in candidates)
answer = max(counts,key=counts.get) # empate: primera respuesta observada
selected['voto'] += int(answer == 4)
oracle += any(row[1] for row in candidates)
print('Problemas de prueba:',len(test_groups))
print('Acierto:',{k:v/len(test_groups) for k,v in selected.items()})
print('Cobertura oráculo:',oracle/len(test_groups))
print('Primer error localizado:',first_hits,'de',first_total)Oracle coverage reports whether any correct answer exists; it is not realizable without access to truth. Here the goal is always 4 and any −1 increment prevents recovery, since the remainder can add at most one per step. Outcome scoring can therefore learn to recognize the correct answer almost directly: matching coverage does not prove a general ORM is perfect. Problems are instances of the same task and evaluation does not represent generalization to new GSM8K problems. Values are terminal-success scores; a low minimum may occur after the first error, not exactly at it. Inspect output before drawing conclusions.
Local lab: a prefix verifier
The campaign uses solutions and ORM published in the previous lesson. It selects sample 0 from each of the first 300 training problems and splits by nonempty lines, retaining every prefix. This yields 4297 prefixes and 34,376 continuations if the source file is exactly the published one. A LaTeX line or heading counts as a step: the experiment measures this segmentation, not ideal semantic units. The first 270 problems train and the last 30 validate the PRM. Selection testing uses distinct test problems already scored by the ORM.
Download into one folder the label generator, trainer, evaluator, human data selector, and first-error evaluator. You also need the v2 extractor, its dependency, training samples, and ORM test scores. Retain the Qwen2.5-1.5B-Instruct and Qwen2.5-0.5B-Instruct revisions pinned in the previous lesson. Directories $SNAPSHOT_15 and $SNAPSHOT_05 must point to their respective snapshots; the generator verifies revision and saves configuration for prefix-level resumption.
python generate_prm.py --samples orm_train_hf_b256.jsonl.gz --model-path "$SNAPSHOT_15" --output prm_smoke_labels --problems 10
python train_prm.py --labels prm_smoke_labels --samples orm_train_hf_b256.jsonl.gz --model-path "$SNAPSHOT_05" --output prm_smoke_adapter --smoke
python generate_prm.py --samples orm_train_hf_b256.jsonl.gz --model-path "$SNAPSHOT_15" --output prm_labels
python train_prm.py --labels prm_labels --samples orm_train_hf_b256.jsonl.gz --model-path "$SNAPSHOT_05" --output prm_adapter
python evaluate_prm.py --scores orm_test_scores.jsonl.gz --model-path "$SNAPSHOT_05" --adapter prm_adapter --output prm_evaluation
The retained local generation ran with the batched vLLM runner, not the first Transformers command. Its 4297 prefixes and 34,376 continuations are in the restorable package, with manifest and hashes. ZIP SHA256 is 2dced63cc359fad63da475557f74a4a512e19a92802d8ce0014091ebbc12d4e0; it was extracted and the provenance and extraction audit rerun on the result. Also retain the preceding lesson’s input sample file, distributed separately. Seeds and backend are recorded in the protocol; regeneration does not guarantee identical tokens.
The extractor recognized 24,624 of 34,376 continuations and 5099 reached the generation limit; these counts measure extraction and truncation, not PRM accuracy. No answer was recognized for 228 prefixes, excluded from fitting for lack of labels; each of 300 problems retains at least one prefix with some extraction. The rate learned by the verifier is conditional on recognized continuations, a particularly relevant limitation if abstentions are not random.
The trainer publishes a complete checkpoint every hundred batches and at each epoch’s end. It saves adapter, optimizer, random generators, and position in data order, with component hashes. If interrupted, repeat the same training command with --resume; it first checks the manifest and resumes the last valid checkpoint. If none was published, training starts again from base. An incomplete temporary directory does not count as a checkpoint.
The first two commands are a separate ten-problem installation test; the evaluator rejects that adapter as a campaign result. Each prefix receives eight continuations at temperature 0.8 and at most 256 tokens. The extractor compares the concatenated solution with the reference and may abstain. Training averages only recognized continuations and weights each prefix by their count; it thus estimates success conditional on extraction, not unconditional value if abstentions are selective. An incomplete campaign is insufficient: the trainer checks the prefix list and rejects missing files. Beyond 768 tokens the evaluator truncates from the left to retain the end of the prefix; this can remove part of the prompt and is recorded as a limitation. Validation loss and calibration table by score tenths are saved. Counts weight recognized continuations, but these share prefixes and problems and must not be treated as independent observations. None of those metrics measures error localization.
The evaluator compares four PRM rules, the preceding lesson’s ORM, and voting on the same eight candidates per problem; it also shows oracle coverage. For each it uses the first candidates and resamples whole problems for intervals. If a selector chooses an unextracted answer, it counts as incorrect and is recorded separately. Voting excludes unextracted answers and abstains only if none remain. This may undervalue methods that select unextracted outputs: report their frequency and inspect those cases. The product is computed by summing logarithms without changing ordering.
Actual fitting used 3662 training prefixes and 407 validation prefixes with at least one recognized continuation. Weighted validation binary loss was 0.688; it measures fit to approximate labels, not step correctness. Held-out evaluation retained 200 problems and 1600 candidates. With eight candidates, the PRM minimum was correct on 43.5% of problems, ORM on 48%, voting on 66%, and oracle coverage was 73%. In those same selections an answer could not be extracted in 45%, 44%, and 10.5% of cases, respectively. These figures describe this sample and extractor; the oracle has access to the answer and is not an available selector.
The portable selection and adapter package contains all 200 scored groups, protocol, learned adapter, and tokenizer, without base weights. Its SHA256 is 209b1d50cba89d14ea2ef38e659e9b6650119090667e8bcaef615955eadc6c9a. Exported configuration replaces the local model path with its public identifier and retains the original fingerprint in the manifest. The packager restored files and reran the selection auditor, using preceding lesson scores. As an additional check, the restored adapter was loaded on CPU: one score differed by 0.0044 from the GPU-saved score; identity across devices is not claimed.
For external process evaluation, download original file phase2_test.jsonl from the PRM800K repository. The selector verifies SHA256, takes the first 50 eligible solutions from distinct problems, and finds the first erroneous step rated by human annotators. It excludes cases where the first step is already wrong and requires a match with the original proposal. The model scores all steps in the original solution, including those after the first error; only the first human error index is used as reference.
python select_prm800k.py --input phase2_test.jsonl --output prm800k_50.json
python evaluate_first_error.py --data prm800k_50.json --model-path "$SNAPSHOT_05" --adapter prm_adapter --output first_error.json
An assistant reviewed 50 GSM8K solutions and other assistants performed an independent second review without seeing the first labels: cases 0–24 and 25–49. They agreed on 47 of 50 indices, including solutions with no identified error. An explicit adjudication retains both labels and explains three disagreements; its manifest fixes provenance and hashes, and the script reconstructs files. One solution is excluded from scoring because its statement allows two referents for “one quarter.” Of the other 49, a first error is identified in 19; 15 of those 19 have no flagged ambiguity. To evaluate them use --data assistant_audit_50_adjudicated.json: the evaluator computes localization among the 19 scorable error cases and a separate sensitivity analysis excluding ambiguous ones. Always choosing a minimum cannot determine whether a solution has no errors.
One untruncated solution with an extracted answer was selected per problem, prioritizing shorter ones: the sample facilitates inspection but does not represent the original distribution. Both reviews and adjudication are assistant judgments, not human annotations; PRM800K is a distinct external contrast.
The external sample comes from MATH, not GSM8K solutions generated for this campaign. The selector takes 50 distinct problems with an identifiable first negative human label, excludes cases whose first negative is the first step, and requires at least one later step; it therefore does not represent all dataset errors. An earlier neutral label is not counted as negative, so “first negative” does not guarantee the first mathematically incorrect step. PRM800K labels are human according to their authors; assistant GSM8K reviews are identified separately. The two measurements have different distributions and procedures. A low localization result is informative, not a reason to change criteria after seeing test.
In the retained run, the PRM minimum matched the assistant-adjudicated first error in 4 of 19 scorable error cases; excluding ambiguous cases gave 3 of 15. None of their 248 prefixes was truncated. On the external PRM800K sample it matched the first negative human label in 4 of 50 cases (8%; bootstrap interval 2% to 16%). There, 83 of 800 prefixes were truncated from the left across 18 solutions: the verifier lost some context in those cases, a material limitation on the contrast. See assistant review and PRM800K reports, their respective external audits, and the aggregate auditor. The auditor reconstructs metrics from saved scores; it does not rerun the network or certify annotations.
Exercises
Step 1 of 2. What is the expectation of the mean?
def aggregate_step_scores(scores, rule):
pass
def best_of_n(candidates, rule):
pass