Reinforcement Learning from Verifiable Rewards › Worked Example: A Verifier That Teaches the Wrong Lesson

Michael BrenndoerferNovember 29, 202613 min read
Language AI HandbookAll chapters
Part 40 of 67Reasoning Post-Training and Verifiable Rewards
Chapter 300Reinforcement Learning from Verifiable Rewards › Worked Example: A Verifier That Teaches the Wrong Lesson
Reading section 7 of 12 · Worked Example: A Verifier That Teaches the Wrong Lesson · 13 minSection 7 of 12 · 13 min

Section 7 of 12 · 13 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

The following seeded CPU example uses integer addition. A policy chooses among response templates. A checker sees the rendered text and the answer key, while evaluation compares the committed answer with the key. The model under study is a categorical policy over templates.

The design has three deliberately separated layers:

  • Responses: literal strings, rendered from templates and the problem's operands.
  • Verifier scores: computed by regex over the string, with no access to the strategy's intent.
  • Hidden labels: computed from the answer the response actually claims, which the verifier never sees.

The templates provide an explicit committed answer for the evaluation label. The example checker receives the string and gold answer, so it has to infer what the response commits to from the string.

The task and the response space

We start with eight addition problems and a small set of response strategies. Each strategy is a template that produces a string from the operands, plus a record of the final answer that string actually commits to.

PythonIn [6]
CollapseExpand
import re

import numpy as np
import pandas as pd

# Eight harmless integer addition problems. The gold answer is a + b.
PROBLEMS = [(3, 4), (5, 2), (6, 3), (2, 9), (7, 5), (4, 4), (8, 3), (6, 6)]
GOLD = [a + b for a, b in PROBLEMS]

Each fixture contains two small positive integers. The gold answer is their sum. The renderer returns the response text and its committed answer. The hidden correctness label is computed later by comparing that answer with the gold answer.

PythonIn [7]
CollapseExpand
STRATEGIES = [
    "bare",  # just the number
    "sentence",  # a plain declarative answer
    "cot",  # shows the arithmetic, then answers correctly
    "hedge",  # names the right number first, then commits to a wrong one
    "wrong",  # plain wrong answer
    "abstain",  # declines to answer
    "cot_wrong",  # shows correct arithmetic, then commits to a wrong answer
    "trailing_truth",  # commits to a wrong answer, then restates the true sum
]


def render(strategy, a, b):
    """Return (response_text, committed_claim).

    The claim is the answer the response ends up asserting, or None if it
    declines to answer. The verifier never sees this value.
    """
    n = a + b
    if strategy == "bare":
        return f"{n}", n
    if strategy == "sentence":
        return f"The answer is {n}.", n
    if strategy == "cot":
        return f"First compute {a} + {b} = {n}. The answer is {n}.", n
    if strategy == "hedge":
        return f"{n}, or maybe {n + 1}. I will go with {n + 1}.", n + 1
    if strategy == "wrong":
        return f"The answer is {n + 1}.", n + 1
    if strategy == "abstain":
        return "I am not sure. I cannot determine the answer.", None
    if strategy == "cot_wrong":
        return (
            f"First compute {a} + {b} = {n}. Hmm, but the answer is {n + 1}.",
            n + 1,
        )
    if strategy == "trailing_truth":
        return f"The answer is {n + 1}. To confirm, {a} + {b} = {n}.", n + 1
    raise ValueError(strategy)

Let's look at what these strings actually look like for the first problem.

ConsoleOut [8]
CollapseExpand
bare            claim=   7  |  7
sentence        claim=   7  |  The answer is 7.
cot             claim=   7  |  First compute 3 + 4 = 7. The answer is 7.
hedge           claim=   8  |  7, or maybe 8. I will go with 8.
wrong           claim=   8  |  The answer is 8.
abstain         claim=None  |  I am not sure. I cannot determine the answer.
cot_wrong       claim=   8  |  First compute 3 + 4 = 7. Hmm, but the answer is 8.
trailing_truth  claim=   8  |  The answer is 8. To confirm, 3 + 4 = 7.

The cot response shows the addition and gives the right sum. The hedge response names the correct number first and then commits to the wrong value. The trailing_truth template commits to a wrong value and later mentions the correct sum. Abstention has no committed answer.

Three verifiers, three blind spots

We implement three deliberately narrow heuristics for the toy examples. The fixtures contain only small positive integers and at most a few digit groups. For instance, the first-integer heuristic finds 7 in the sentence “The answer is 7.” and 3 in “First compute 3 + 4 = 7.” A production parser must specify the treatment of signs, decimal points and overlong input separately.

PythonIn [9]
CollapseExpand
NUMBER = re.compile(r"\d+")


def first_integer(text):
    hits = NUMBER.findall(text)
    return int(hits[0]) if hits else None


def last_integer(text):
    hits = NUMBER.findall(text)
    return int(hits[-1]) if hits else None


def verifier_first_int(text, gold):
    return int(first_integer(text) == gold)


def verifier_last_int(text, gold):
    return int(last_integer(text) == gold)


def verifier_contains(text, gold):
    return int(re.search(rf"\b{gold}\b", text) is not None)


VERIFIERS = {
    "first_int": verifier_first_int,
    "last_int": verifier_last_int,
    "contains": verifier_contains,
}

Each verifier embodies a different theory of where the answer lives in a response:

  • first_int takes the first recognized digit group. It works for a bare answer in this fixture and can mistake the first operand for an answer.
  • last_int takes the last recognized digit group. It can credit a late mention even when the response explicitly committed to a different value.
  • contains checks whether the gold digit string occurs at a word boundary on both sides. Mentioning the gold number does not show commitment to that answer.

Auditing verifiers against hidden labels

Each strategy is rendered for each problem. The audit records the independent correctness label and the output of each verifier. Per-strategy summaries reveal failures that an overall mean can hide.

PythonIn [10]
CollapseExpand
records = []
for strategy in STRATEGIES:
    for (a, b), gold in zip(PROBLEMS, GOLD):
        text, claim = render(strategy, a, b)
        row = {
            "strategy": strategy,
            "gold": gold,
            "claim": claim,
            "hidden_correct": int(claim is not None and claim == gold),
        }
        for name, fn in VERIFIERS.items():
            row[name] = fn(text, gold)
        records.append(row)

audit = pd.DataFrame(records)

The hidden column gives the fraction of correct commitments for each strategy. The other three score columns give the fraction of problems on which each checker awarded credit.

ConsoleOut [11]
CollapseExpand
      strategy  hidden  first_int  last_int  contains
          bare    1.00       1.00      1.00      1.00
      sentence    1.00       1.00      1.00      1.00
           cot    1.00       0.00      1.00      1.00
         hedge    0.00       1.00      0.00      1.00
         wrong    0.00       0.00      0.00      0.00
       abstain    0.00       0.00      0.00      0.00
     cot_wrong    0.00       0.00      0.00      1.00
trailing_truth    0.00       0.00      1.00      1.00

Compare the hidden column with the three checkers. first_int pays hedge and rejects cot on all eight problems. last_int accepts all the correct strategies and also accepts trailing_truth. contains accepts bare, sentence, and cot, along with three wrong commitments: hedge, cot_wrong, and trailing_truth. It rejects wrong and abstain.

Now let's quantify the errors directly with a confusion matrix over all 64 (strategy, problem) pairs.

PythonIn [12]
CollapseExpand
def confusion(df, column):
    tp = int(((df[column] == 1) & (df.hidden_correct == 1)).sum())
    fp = int(((df[column] == 1) & (df.hidden_correct == 0)).sum())
    fn = int(((df[column] == 0) & (df.hidden_correct == 1)).sum())
    tn = int(((df[column] == 0) & (df.hidden_correct == 0)).sum())
    return tp, fp, fn, tn
ConsoleOut [13]
CollapseExpand
first_int  TP=16 FP= 8 FN= 8 TN=32  precision=0.67  recall=0.67
last_int   TP=24 FP= 8 FN= 0 TN=32  precision=0.75  recall=1.00
contains   TP=24 FP=24 FN= 0 TN=16  precision=0.50  recall=1.00

On these 64 pairs, first_int has both false positives and false negatives. last_int has recall 1.00 and precision 0.75. contains reaches the same recall but has precision 0.50. Precision describes the share of accepted outputs whose committed answer is correct. Recall describes the share of correct outputs that receive credit. Both depend on how the audit examples are sampled. The code reports an undefined rate as nan if its denominator is zero.

Training a policy against a broken verifier

Now we put a policy over these eight strategies and run policy gradient against one of the verifiers. The policy is a softmax over strategy indices, shared across all problems, which is a simplification. A real language model conditions on the prompt. With one distribution over strategies, changing the reward affects the mix of response styles applied to the entire problem set.

The reward vector for a verifier is the average payout of each strategy across all problems.

PythonIn [14]
CollapseExpand
n_strategies = len(STRATEGIES)

reward_first_int = np.array(
    [audit[audit.strategy == s]["first_int"].mean() for s in STRATEGIES]
)
reward_hidden = np.array(
    [audit[audit.strategy == s]["hidden_correct"].mean() for s in STRATEGIES]
)

reward_table = pd.DataFrame(
    {
        "strategy": STRATEGIES,
        "first_int_reward": reward_first_int,
        "hidden_label_reward": reward_hidden,
    }
)
ConsoleOut [15]
CollapseExpand
      strategy  first_int_reward  hidden_label_reward
          bare              1.00                 1.00
      sentence              1.00                 1.00
           cot              0.00                 1.00
         hedge              1.00                 0.00
         wrong              0.00                 0.00
       abstain              0.00                 0.00
     cot_wrong              0.00                 0.00
trailing_truth              0.00                 0.00

The first_int reward agrees with the hidden-label reward on six of the eight strategies. It misses the correct cot and accepts the incorrect hedge. The highest-reward strategies under the first-integer verifier are bare, sentence, and hedge, each at 1.00.

The training loop applies a REINFORCE-style score-function update to the one-step bandit, using the batch’s own mean reward as its baseline. To compare rewards on this fixture, both runs start from a uniform policy and use the same seed, batch size, learning rate, and number of updates.

PythonIn [16]
CollapseExpand
def softmax(z):
    z = z - np.max(z)
    e = np.exp(z)
    return e / e.sum()


def train_bandit(objective, steps=600, lr=0.5, batch=256, seed=0):
    """Policy gradient on a tabular bandit. Returns final policy and traces.

    `objective` is the per-strategy reward the policy optimizes. The traces
    also record what that policy scores on the other reward signals.
    """
    if batch < 1:
        raise ValueError("batch must be a positive integer")

    rng = np.random.default_rng(seed)
    n = len(objective)
    theta = np.zeros(n)
    trace = {"objective": [], "first_int": [], "hidden": []}

    for _ in range(steps):
        p = softmax(theta)
        idx = rng.choice(n, size=batch, p=p)
        advantage = objective[idx] - objective[idx].mean()

        grad = np.zeros(n)
        np.add.at(grad, idx, advantage)
        grad -= advantage.sum() * p
        theta += lr * grad / batch

        p = softmax(theta)
        trace["objective"].append(float(p @ objective))
        trace["first_int"].append(float(p @ reward_first_int))
        trace["hidden"].append(float(p @ reward_hidden))

    return softmax(theta), {k: np.array(v) for k, v in trace.items()}

The update uses the sample mean as a baseline. The log-softmax gradient for a sampled index ii is the corresponding one-hot vector minus the current probability vector pp. This explains the grad -= advantage.sum() * p term. The centered advantages sum to zero in exact arithmetic. Each of the BB independent draws contributes to its own baseline, so this estimator is biased by a multiplicative factor. To see it, let RiR_i be draw ii’s reward and Si=∇θlog⁡p(Ai)S_i=\nabla_\theta\log p(A_i) be its score-function vector. The expected reward-only gradient is g=E[RiSi]g=\mathbb{E}[R_iS_i]. For the batch mean Rˉ\bar R, the contribution of the iith reward to E[RˉSi]\mathbb{E}[\bar R S_i] is g/Bg/B. Every other draw is independent of SiS_i, whose expectation is zero, so the other terms vanish. Thus E[(Ri−Rˉ)Si]=(1−1/B)g\mathbb{E}[(R_i-\bar R)S_i]=(1-1/B)g. In this softmax example the exact logit gradient has entries pj(rj−∑kpkrk)p_j(r_j-\sum_k p_kr_k), where rjr_j is strategy jj’s reward. The probability factor pjp_j matters when comparing an empirical gradient to the exact one.

One run uses the first-integer verifier. The other uses the hidden correctness labels as an oracle reward.

PythonIn [17]
CollapseExpand
policy_verifier, trace_verifier = train_bandit(reward_first_int, seed=1)
policy_truth, trace_truth = train_bandit(reward_hidden, seed=1)
uniform = np.full(n_strategies, 1.0 / n_strategies)

Let's see what each policy scores on each signal.

ConsoleOut [18]
CollapseExpand
               policy  verifier_score  true_accuracy
uniform (no training)           0.375          0.375
 trained on first_int           0.994          0.503
     trained on truth           0.441          0.994

With seed 1 in both runs, the verifier-trained policy reaches verifier score 0.994 and expected accuracy 0.503 on the uniform mix of eight problems. Its probability of choosing hedge is about 0.492. The policy trained on hidden labels reaches expected accuracy 0.994 and verifier score 0.441. These scores average over the policy's strategy probabilities and the toy problem mix.

Reading the results

Two figures make the mechanism visible. The first shows the final policy distribution over strategies for both runs.

VisualizationOut [19]
CollapseExpand
Grouped bar chart comparing final policy probability for eight response strategies under a flawed verifier versus hidden labels.
Final probability mass over response strategies after policy gradient training. Training against the first-integer verifier (left bar of each pair) concentrates mass on hedge (about 0.49) plus bare and sentence (about 0.29 and 0.21) and drives chain-of-thought to about 0.001. Training against hidden labels (right bar of each pair) puts about 0.55 on the worked-answer strategy and about 0.24 and 0.20 on bare and sentence, respectively. Hedge ends near 0.001. Both runs use seed 1.

With the seed held fixed, the correct cot strategy finishes at probability 0.554 under the hidden-label objective. It finishes near 0.001 under the first-integer objective, where the checker reads an operand. In that run, hedge ends at about 0.492 even though it gives a wrong answer on every problem.

The second figure traces the verifier score and true accuracy on the two trained policies across the 600 policy gradient steps.

VisualizationOut [20]
CollapseExpand
Four training curves. The two optimized scores nearly overlap along the top. Accuracy under verifier training and verifier score under hidden-label training decline after their early peaks.
Training curves for two policies over 600 policy gradient steps. Circles denote training on the first-integer verifier and squares denote training on hidden labels. Solid lines show verifier score and dashed lines show expected accuracy. The verifier-trained policy's verifier score climbs to about 0.99 while its expected accuracy peaks near 0.61 around step 96 and finishes near 0.50. The hidden-label policy's verifier score ends at about 0.44 while its expected accuracy climbs to about 0.99. Both runs use seed 1. The verifier-trained policy's verifier score and the hidden-label policy's accuracy nearly overlap at the top.

The verifier-trained run finishes near 0.99 on the verifier and 0.50 on expected accuracy. The hidden-label run finishes near 0.44 on the verifier and 0.99 on expected accuracy. Both metrics can improve over their uniform starting values while still ranking the two trained policies differently.

Scope of the arithmetic experiment

The same eight-strategy policy is applied to every prompt. The example uses no language model, token-level update or KL penalty. The two metrics rank the learned policies in opposite orders for this matched seed. Changing the sampling seed or learning rate can change how much probability goes to each of the three equally rewarded strategies under the flawed verifier. The size of the accuracy gap depends on that mix.

Comments

Add to the conversation

A question, a correction, or an example from your own work.

No comments yet. Be the first to share your thoughts!

Newsletter

Stay up to date

Get new articles, book updates, and notes on AI and technology.

Unsubscribe at any time. Privacy policy