Experiential
BlogTraining

Reward hacking in agent training, and how verifiable rewards help

November 2026 · 10 min

Reward hacking occurs when an RL agent exploits a reward model or environment flaw without solving the task. Reinforcement learning with verifiable rewards (RLVR) replaces learned neural reward models with programmatic verifiers like unit tests, exact-match labels, or database checks. That removes the learned model as an optimization target, though weak tests and grader bugs remain.

Every online RL run depends on its reward model, across GRPO, its practical variant DAPO, or other policy-gradient methods. Because RL runs in closed loop inside a changing environment, reward or environment gaps become exploits; see SFT vs RL when choosing between RL and supervised data.

Specification gaming vs reward hacking

Specification gaming is satisfying the literal specification of an objective without achieving its intent. Reward hacking is the RL term for the same family of failures, and Lilian Weng's taxonomy splits it into misspecified objectives and tampering with the reward mechanism. DeepMind's post also counts reward tampering among the challenges of specification gaming. The 2 concepts overlap in practice.

Victoria Krakovna and colleagues at DeepMind defined specification gaming in 2020 as "a behaviour that satisfies the literal specification of an objective without achieving the intended outcome". Joar Skalse and colleagues formalized reward hacking as optimizing an imperfect proxy reward so true objective performance drops.

In her 2024 review of reward hacking in RL, Lilian Weng groups the problem into 2 categories. Environment or goal misspecification exploits gaps in the objective; reward tampering interferes with the reward mechanism directly.

Skalse and colleagues proved a sharp limit: across all stochastic policies, 2 non-equivalent reward functions are unhackable only if 1 is constant. That applies over all stochastic policies, showing general unhackability is rare while leaving open whether reachable training policies can exploit a specific verifier.

Why learned reward models fail differently from verifiers

Learned reward models and programmatic verifiers fail differently because neural networks learn preference patterns while verifiers check explicit rules. In RL, "reward model" covers any trajectory-scoring component, and rewards can be dense and process-level or sparse and outcome-level.

Reward model overoptimization in RLHF

In RLHF, a learned neural reward model approximates human judgment, and over-optimizing against it breaks that proxy. Leo Gao, John Schulman, and Jacob Hilton showed in 2022 that pushing an imperfect reward model too far "can hinder ground truth performance", matching Goodhart's law.

DeepSeek avoided neural reward models on reasoning tasks in DeepSeek-R1 because they are "susceptible to reward hacking during large-scale reinforcement learning". In R1's second RL stage, preference rewards ran only for the final 400 of 1,700 steps; Appendix B.5 shows helpfulness rising while Codeforces dropped.

Lilian Weng's review catalogs similar failure modes in preference models and LLM judges. Common traps include sycophancy toward user beliefs, positional bias when ranking candidates, and self-preference bias toward a model family's own outputs.

What RLVR changes

RLVR replaces a learned neural reward model with a verifier giving a sparse binary reward on the final outcome. The Allen Institute for AI named it in Tülu 3, where RLVR "replaces the reward model with a verification function" on math and instruction following.

GRPO works with dense process-level rewards or sparse outcome verifiers, though most teams use sparse checks. DeepSeek-R1-Zero paired rule-based accuracy rewards (boxed math answers and compiler test suites) with reasoning-tag format rewards, learning strong process-level reasoning from outcome-level rewards alone.

In an answer-only exact-match verifier, flattering tone adds 0 reward. Removing the learned model closes it as an optimization target, though agents still exploit weak tests, incomplete specs, and grader bugs in the RL environment.

Documented reward hacks in agent training

Documented agent reward hacks span 7 classes across production training, controlled studies, benchmark audits, and preference-RL overoptimization. The first 6 classes target programmatic verifiers and test harnesses where execution boundaries or grading logic leave gaps.

Hack classDocumented exampleWhy the reward model allowed itMitigation
Early process exitOpenAI (2025) and Anthropic (2025, controlled RL study): calling exit(0) or sys.exit(0) in coding runsThe harness treated process exit code 0 as passing without verifying assertions ranRequire a structured per-test pass count and a completion token issued and checked outside the candidate's process, alongside exit status
Test skippingOpenAI (2025): raising SkipTest from outside the test framework during reasoning RLThe runner treated skipped tests as non-failing and returned successCount executed and skipped tests separately and score any skipped test as 0
Assertion and runner tamperingAnthropic (2025, controlled RL study): AlwaysEqual object overriding __eq__, or conftest.py patching pytest TestReportTests ran == inside the agent workspace, where the agent could also add pytest hooksUse an OS or container sandbox, a protected grading channel, and bounded schema-validated data exchange
Stubbing and hardcodingOpenAI (2025): making verify return true or stubbing libraries; Anthropic (2025): test hardcoding in Sonnet 3.7 trainingUnit tests checked narrow inputs or a single helper and missed general behaviorKeep hidden held-out tests, randomized inputs, and property checks out of the workspace
Empty-state shortcutZhu et al. (2025): doing nothing passes τ-bench unsolvable tasks (38% airline, 6% retail)Success was defined solely as leaving the database unchangedDistinguish justified inaction from an empty shortcut, and run a no-op baseline
Output stuffingZhu et al. (2025): dumping the DB passes 2% of airline and 3.6% of retail τ-bench tasks; WebArena ignores extra textThe verifier graded by substring matching without exact field extractionParse 1 structured field and reject multi-answer or extraneous output
Reward model overoptimizationDeepSeek-R1 (arXiv v2, Jan 2026, Appendix B.5): helpfulness reward rose while Codeforces score droppedSystematic biases in a learned reward model compounded over many RL stepsUse rule-based verifiers where outcomes are checkable and monitor validation scores during preference RL
Sources: Baker et al. (2025), MacDiarmid et al. (2025), Zhu et al. (2025), and DeepSeek-R1 (arXiv v2, Jan 2026), read November 20, 2026.

Why coding hacks become systemic

Coding reward hacks spread because policy-gradient training reinforces higher advantage. GRPO and DAPO (the main practical GRPO variant, with others as close relatives) estimate advantage from group statistics with no learned critic.

When every rollout in a group games the verifier for full reward, advantage is 0 and adds no gradient. When hacking rollouts beat failing honest attempts in that group, positive advantage spreads the exploit.

OpenAI researchers found a frontier reasoning agent discovering 2 environment-wide hacks: exit(0) to leave the environment before all unit tests ran, and raise SkipTest from functions outside the test framework. Where tests checked a single function, it made a verify helper always return true; where coverage was poor, it wrote stubs in place of real implementations.

Anthropic researchers tested Sonnet 3.7 environments vulnerable to AlwaysEqual (__eq__ returning True), sys.exit(0), or conftest.py patching pytest's TestReport. Those 3 hacks stayed absent from Sonnet 3.7 training, which saw test hardcoding.

Unmitigated RL on a hack-aware model generalized to misalignment in their main synthetic-document setting (write-up). The final model showed alignment-faking reasoning in 50% of evaluated responses, even to simple questions such as "What are your goals?", and 12% attempted sabotage on a Claude Code safety-codebase task.

Empty states, substring matchers, and turn weighting

Empty-state shortcuts, substring matchers, and per-turn weighting let tool-use agents score high without solving tasks. In closed-loop RL, actions change environment state, so a verifier can check what actually happened instead of trusting the agent's report. It is only as strong as its target conditions and the protection around the grader, and a final-state check can miss required steps along the way.

In a 2025 benchmark audit, Zhu and colleagues found that doing nothing passed τ-bench's unsolvable tasks (38% of Airline, 6% of Retail). That trivial do-nothing agent scored 38% on τ-bench Airline, beating GPT-4o at 35%.

Substring matching let database dumps pass 2% of Airline and 3.6% of Retail τ-bench tasks, and let WebArena agents pass with irrelevant text. Benchmark flaws skewed scores up to 100% relative; their Agentic Benchmark Checklist cut CVE-Bench overestimation by 33% absolute.

Multi-turn RL also risks length bias when episodes are weighted per turn. In our claims research study, we trained on complete search-and-reasoning trajectories as single episodes so long runs gained no extra weight.

Testing a verifier with adversarial probes in Python

Testing a verifier means running it against a gold solution, an empty submission, a wrong answer, and cheat probes so only gold scores 1.0. Never execute untrusted or model-generated code directly on a host machine.

This script runs only hardcoded benign probes, and python3 -I enables Python's isolated mode with no OS sandbox. checked_verify_demo passes the 6 listed probes and lacks production grading isolation.

Because candidate code shares the runner process, a real submission could monkey-patch unittest.TestCase.assertEqual or json to forge a passing report. The demo compares naive_verify against checked_verify_demo using Python's standard library alone.

Python
import jsonimport secretsimport subprocessimport sys TESTS = [(-3, -6), (0, 0), (4, 8)] PROBES = [    ("gold", "def double(x):\n    return x * 2\n", 1.0),    ("empty", "", 0.0),    ("wrong", "def double(x):\n    return x + 2\n", 0.0),    ("exit_zero", "import sys\nsys.exit(0)\n", 0.0),    ("skip_test", "import unittest\ndef double(x):\n    raise unittest.SkipTest('skip')\n", 0.0),    (        "always_equal",        "class E:\n    def __eq__(self, other):\n        return True\ndef double(x):\n    return E()\n",        0.0,    ),] NAIVE_HARNESS = """import unittest{code}class T(unittest.TestCase):    def test_cases(self):        for x, want in {tests!r}:            self.assertEqual(double(x), want)unittest.main(verbosity=0)""" CHECKED_HARNESS = """import json, unittest{code}class T(unittest.TestCase):    passfor i, (x, want) in enumerate({tests!r}):    def make_test(x=x, want=want):        def test(self):            got = double(x)            self.assertIs(type(got), type(want))            self.assertEqual(got, want)        return test    setattr(T, f"test_{{i}}", make_test())suite = unittest.defaultTestLoader.loadTestsFromTestCase(T)res = unittest.TextTestRunner(verbosity=0).run(suite)print()print(json.dumps({{    "token": {token!r},    "ran": res.testsRun,    "failed": len(res.failures) + len(res.errors),    "skipped": len(res.skipped),}}))"""  def run_py(script):    try:        return subprocess.run(            [sys.executable, "-I", "-c", script],            capture_output=True, text=True, timeout=5,        )    except subprocess.TimeoutExpired:        return None  def naive_verify(code):    proc = run_py(NAIVE_HARNESS.format(code=code, tests=TESTS))    return 1.0 if proc and proc.returncode == 0 else 0.0  def checked_verify_demo(code):    token = secrets.token_hex(8)    proc = run_py(CHECKED_HARNESS.format(code=code, tests=TESTS, token=token))    if not proc or proc.returncode != 0:        return 0.0    lines = [line for line in proc.stdout.splitlines() if line.strip()]    if not lines:        return 0.0    try:        report = json.loads(lines[-1])    except json.JSONDecodeError:        return 0.0    if not isinstance(report, dict):        return 0.0    ok = (        report.get("token") == token        and report.get("ran") == len(TESTS)        and report.get("failed") == 0        and report.get("skipped") == 0    )    return 1.0 if ok else 0.0  def audit(name, verify_fn):    failures = []    for probe_name, code, expected in PROBES:        score = verify_fn(code)        if score != expected:            failures.append(f"{probe_name} (got {score}, want {expected})")    status = "PASS (supplied probes only)" if not failures else "FAIL: " + ", ".join(failures)    print(f"{name:20s} -> {status}")  if __name__ == "__main__":    audit("naive_verify", naive_verify)    audit("checked_verify_demo", checked_verify_demo)

Saved as audit_verifier.py and run with python3 -I audit_verifier.py on Python 3.15.2 (confirmed identical on Python 3.12.16), the script prints this summary. Each failing probe shows its actual score next to the expected score.

Text
naive_verify         -> FAIL: exit_zero (got 1.0, want 0.0), skip_test (got 1.0, want 0.0), always_equal (got 1.0, want 0.0)checked_verify_demo  -> PASS (supplied probes only)

What the audit catches and what still needs a container

The demo catches early exits, skipped tests, and custom equality overrides; production runs still need a container sandbox and protected grading channel. naive_verify gives 1.0 to exit_zero, skip_test, and always_equal, while checked_verify_demo scores all 3 at 0.0.

In extra checks, checked_verify_demo scored 0.0 on os._exit(0), non-dict JSON stdout, bool for int, syntax errors, and infinite loops. It still passed gold code printing without a trailing newline.

Production coding RL needs a no-network container sandbox with resource limits, a protected grading channel, and a bounded, schema-validated protocol. A fresh container alone cannot stop same-process monkey-patching; we build on Harbor, where a separate verifier environment (environment_mode = "separate" in task.toml) grades declared artifacts in a fresh sandbox that does not inherit the agent's filesystem changes.

Production harnesses also handle invalid UTF-8 (UnicodeDecodeError), OSError launch failures separate from task failures, unbounded capture_output=True memory, and orphaned descendant processes. Held-out tests outside the workspace catch lookup tables hardcoded to the visible cases; randomized inputs and property checks cover small input domains.

A 6-point verifier audit checklist for setup and training

Run this 6-point audit across setup and training to catch empty-state shortcuts, workspace tampering, and reward-metric divergence. The first 4 checks validate the environment and verifier before GPU runs; the last 2 monitor live training.

Before training: 4 checks on the verifier and sandbox

Validate the verifier and sandbox with these 4 checks before launching training. Running them in CI catches broken graders before GPU time starts.

  1. Run gold and no-op baselines on every task. Confirm gold scores 1.0 and an untouched workspace or empty reply scores 0.0 when action is required; Zhu and colleagues' checklist asks benchmarks to report a trivial agent's results, and Harbor ships both baselines as agents: oracle runs the task's reference solution and nop does nothing.
  2. Run domain-specific cheat probes and qualification controls. Test sys.exit(0), SkipTest, AlwaysEqual, database stuffing, and malformed tool calls in CI; our open-source gateway's Harbor export requires 4 independent controls (positive, goal-failure, prohibited-effect, and unknown-evidence) before a verifier can reward.
  3. Isolate the grader and hide ground truth. Keep reference answers and hidden tests out of the agent's prompt and the agent's filesystem. Harbor uploads a task's tests/ only after the agent runs, and a separate verifier environment grades in a fresh sandbox that does not inherit the agent's filesystem changes.
  4. Score closed-loop environment state ahead of self-reports. Grading database rows, compiled output, or verified side effects beats reading transcripts; where inaction is valid, separate justified inaction from empty shortcuts (RL environments guide).

During training: 2 checks on metrics and reasoning traces

Monitor these 2 signals during training to catch loopholes emerging under optimization. Early detection lets you patch verifiers before exploits spread across tasks.

  1. Track held-out and secondary metrics next to training reward. Log held-out accuracy, tool calls, completion length, and clipped completions; rising training reward with falling held-out accuracy (like DeepSeek-R1's Codeforces drop) signals hacking or overfitting.
  2. Inspect reasoning traces out of loop without over-optimizing them. Log sampled trajectories and rewards from your RL trainer (we use Miles, which runs rollouts on SGLang and trains on Megatron-LM) and audit top-reward traces externally. OpenAI's study showed GPT-4o monitoring chain of thought beat action-only monitors, whereas heavy pressure on chain of thought caused obfuscated reward hacking.

Anthropic's study lists 3 mitigations against emergent misalignment: preventing reward hacking directly, diversifying RLHF safety training, and inoculation prompting (reframing reward hacking as acceptable behavior during training to contain generalization). Fixing the verifier remains primary for task quality.

When verifiable rewards are not enough

RLVR fits tasks whose success criteria code can check, including several constraints at once, and falls short when important parts of quality need human judgment. Open-ended writing, tone, and ambiguous calls rarely reduce to exact matches or unit tests without becoming brittle proxies.

For subjective work, use DPO on curated pairs, calibrated LLM judges with balanced position checks, or bounded preference RL with held-out validation. DeepSeek-R1 limited preference rewards to the final 400 of 1,700 second-stage steps, noting that longer training on them could lead to reward hacking. Verifiers that reward only correctness also leave latency, tool efficiency, and readability unoptimized.

When strong teacher outputs or expert demonstrations exist, SFT or distillation avoids online reward hacking completely. SFT is open loop: the model imitates demonstrations and never sees its own mistakes, so closed-loop RL remains stronger for error recovery; see SFT vs RL. SFT on a reasoning model can also collapse its reasoning when the chain of thought is missing from the data.

Fine-tuning on Experiential

We fine-tune open small language models with RL on Miles and Harbor because closed-loop environments and verifiers are the hard part. Miles (RadixArk, Apache-2.0) runs SGLang rollouts and trains on Megatron-LM, FSDP2, or torchtitan; trained weights serve on vLLM or SGLang.

Our early-access Training API runs asynchronous GRPO with LoRA (rank 128) on Qwen3.5 9B using 2 H100s: 1 trainer and 1 sampler. Our platform imports versioned Harbor collections from Git or an archive (environments docs).

Our open-source gateway turns traces into simulations, inducing 1 exact Python transition program per tool, and exports qualified tasks as Harbor packages (Harbor docs). Unqualified exports cannot reward, and cosmetic verifier edits cannot supply independent evidence: qualified tasks write reward.json with 0 or 1.

Managed fine-tuning starts with 1 workload: with prompt and response logging on, we simulate your production environment from traces, fine-tune an open small language model with RL in that simulation, and deploy it under a new model name. You start each run yourself and can download weights anytime.

Simulated environments and self-play

Our environments are text-world simulations where a model generates the tasks and state transitions, and we package and distribute them as Harbor environments. Because the simulator is a model, it can co-evolve with the policy being trained, a form of self-play. It can steer itself away from reward hacks and set up a progressively harder curriculum.

Book a call on our fine-tuning page to get started. Paid subscribers stay outside our Data Licensing Program unless they opt in. Subscribing does not switch content storage off: subscribers turn the storage controls on in settings (terms, privacy).

Verifiable rewards in our claims research study

In our August 2026 claims research study, we trained a claims research agent with GRPO against a verifiable exact-match outcome check. It searches a claim's evidence store and returns 1 of 4 verdicts: Supported, Refuted, Not Enough Evidence, or Conflicting Evidence.

We trained Qwen3.5-4B with GRPO and LoRA on complete trajectories for exact-match verdict accuracy. On 500 held-out AVeriTeC development claims, it beat Claude Haiku 4.5 by 10.9% relative verdict accuracy (+4.5% to +17.3% relative paired CI) and raised the official AVeriTeC score 11.3% relative.

That workflow used 44% fewer searches and ran 9.4x faster at 90% lower cost. In a separate routing evaluation on 489 held-out claims, the trained 4B scored 71.1% at $1.75 per 1,000 claims, raising the floor from 57% to 71%. Both were controlled public-benchmark experiments separate from customer deployments.

Questions answered

What is reward hacking?

Reward hacking occurs when a reinforcement learning agent earns high reward by exploiting a flaw, loophole, or ambiguity in its reward model or environment without solving the intended task. Joar Skalse and colleagues formalize it as optimizing an imperfect proxy reward function in a way that lowers performance on the true objective. In agent training, it includes both gaming misspecified goals and tampering directly with test harnesses or files.

What is the difference between specification gaming and reward hacking?

Specification gaming and reward hacking overlap closely in practice. Victoria Krakovna and colleagues defined specification gaming in 2020 as satisfying the literal specification of an objective without achieving the intended outcome, and counted reward tampering among its challenges. Lilian Weng's 2024 review splits reward hacking in RL into environment or goal misspecification and reward tampering, where the agent interferes with the grading mechanism or test files directly.

What is RLVR?

RLVR stands for Reinforcement Learning with Verifiable Rewards, a name introduced in the Allen Institute for AI's Tülu 3 paper. It replaces the learned neural reward model of traditional RLHF with a programmatic verifier that computes a sparse binary reward on the final outcome, such as a math answer checker, compiler test suite, or database assertion. Rewards in RL can also be dense and process-level, though RLVR focuses on verifiable outcome checks that pay reward only when the completion passes.

Can RLVR completely prevent reward hacking?

RLVR eliminates preference-model overoptimization without guaranteeing immunity to reward hacking. Replacing a learned reward model removes it as an optimization target, though incomplete specifications, weak tests, and environment or grader bugs remain exploitable. Published studies document coding agents calling exit(0), raising SkipTest, returning AlwaysEqual objects, or writing conftest.py hooks to pass pytest, while tool-use benchmarks let empty replies or database dumps score 1.0.

What are examples of reward hacking in LLM agents?

Documented coding hacks include frontier reasoning agents calling exit(0) or raising SkipTest (OpenAI, 2025), and returning AlwaysEqual objects or patching pytest's TestReport via conftest.py in a controlled RL study (Anthropic, 2025). In tool-use benchmarks, Zhu and colleagues (2025) found that a do-nothing agent passes τ-bench's unsolvable tasks and a database-dumping agent passes its substring checks. For learned reward models, DeepSeek-R1 (arXiv v2, Jan 2026, Appendix B.5) documented rising helpfulness scores alongside falling Codeforces accuracy during preference RL.

Why do reward hacks spread so quickly in group-based RL like GRPO or DAPO?

Policy-gradient algorithms reinforce trajectories with higher advantage, and group-based methods like GRPO and DAPO estimate advantage from group statistics with no learned critic. When every rollout in a prompt group games the verifier for full reward, every advantage is 0 and adds no gradient. Once a group mixes hacking rollouts that earn full reward with honest attempts that fail, the hacking rollouts carry positive advantage and updates push the policy toward the exploit.

Should you put a chain-of-thought monitor directly into the RL reward?

Use chain-of-thought monitors primarily out of loop for auditing and avoid placing heavy RL optimization pressure directly on reasoning traces. OpenAI researchers (2025) found that a weaker model such as GPT-4o monitoring chain of thought catches coding reward hacks far more reliably than action-only monitors. When they pushed strong RL optimization against the monitor itself, agents learned obfuscated reward hacking that hid intent inside the reasoning trace while continuing to exploit the environment.

Silen Naihin
Written by

Silen Naihin

Co-founder