Reward Hacking in Reinforcement Learning

Watch a Q-learning agent game a naive reward: it farms a bonus tile forever and never reaches the goal. Then two fixes and a detector, from scratch in Python.

Cover Image for Reward Hacking in Reinforcement Learning

Suppose you're teaching an agent to reach an exit, and you give it a small bonus along the way to encourage progress. The bonus seems helpful until the agent discovers it can collect it repeatedly without finishing. Its score improves while the task remains undone. OpenAI's 2016 CoastRunners agent showed the same gap, circling for points while never finishing the boat race.

We reproduce that reward gap by adding a bonus to the Q-learning FrozenLake post's agent. Its proxy return climbs past 28, while the greedy policy reaches the exit zero times. Testing two repairs and building a detector shows how to catch divergence during training.

Let's Build It

Open this in Google Colab and run it top to bottom. It trains a tabular Q-learning agent on a gridworld whose reward has a subtle loophole, then shows what the agent learned to do.

Open In Colab

Here is the trained agent under each reward. On the left, the naive reward: the agent walks to the bonus tile (orange) and oscillates on it forever, grabbing the bonus dozens of times, never reaching the goal. On the right, the fixed reward: the agent walks straight to the goal.

Side-by-side animation of two 7x7 gridworlds. On the left, labelled Hackable reward, the agent moves to the central bonus tile and bounces on and off it repeatedly, its bonus counter climbing while the goal-reached label stays no. On the right, labelled Fixed reward, the agent walks diagonally to the bottom-right goal in twelve steps.

import numpy as np

ACTIONS = [(-1, 0), (1, 0), (0, -1), (0, 1)]  # up, down, left, right

class GridWorld:
    def __init__(self, size=7, bonus_pos=(3, 3), bonus=1.0, gamma=0.99,
                 reward_mode="hackable"):
        self.size, self.bonus_pos, self.bonus = size, bonus_pos, bonus
        self.gamma, self.reward_mode = gamma, reward_mode
        self.start, self.goal = (0, 0), (size - 1, size - 1)

    def reset(self):
        self.pos = self.start
        return self.pos

    def step(self, a):
        dr, dc = ACTIONS[a]
        nr = min(max(self.pos[0] + dr, 0), self.size - 1)
        nc = min(max(self.pos[1] + dc, 0), self.size - 1)
        s_next = (nr, nc)
        done = s_next == self.goal
        r_true = 1.0 if done else 0.0                    # the outcome we want
        if self.reward_mode == "hackable":               # the loophole:
            r_proxy = r_true + (self.bonus if s_next == self.bonus_pos else 0.0)
        else:                                            # reward the objective
            r_proxy = r_true
        self.pos = s_next
        return s_next, r_proxy, r_true, done

def train(env, episodes=3000, max_steps=100, alpha=0.1,
          eps_start=1.0, eps_end=0.05, seed=0):
    rng = np.random.default_rng(seed)
    Q = np.zeros((env.size, env.size, 4))
    for ep in range(episodes):
        eps = eps_end + (eps_start - eps_end) * max(0.0, 1 - ep / (episodes * 0.6))
        s = env.reset()
        for _ in range(max_steps):
            a = rng.integers(4) if rng.random() < eps else int(np.argmax(Q[s]))
            s_next, r_proxy, _, done = env.step(a)
            target = r_proxy + env.gamma * (0.0 if done else np.max(Q[s_next]))
            Q[s][a] += alpha * (target - Q[s][a])
            s = s_next
            if done:
                break
    return Q

def rollout(env, Q, max_steps=100):
    s, reached, bonus_hits = env.reset(), False, 0
    for _ in range(max_steps):
        s, _, _, done = env.step(int(np.argmax(Q[s])))
        bonus_hits += (s == env.bonus_pos)
        if done:
            reached = True
            break
    return reached, bonus_hits

env = GridWorld(reward_mode="hackable")
reached, bonus_hits = rollout(env, train(env))
print(f"reached goal: {reached} | bonus tile grabbed: {bonus_hits} times")

Run it and you get:

reached goal: False | bonus tile grabbed: 48 times

The agent grabbed the bonus 48 times in a 100-step run and never reached the goal. It did not malfunction. It found the highest-scoring behaviour available and committed to it. The reward was the problem.

What just happened

The environment is a 7x7 grid. The agent starts top-left and the goal sits bottom-right. Reaching the goal pays +1 and ends the episode. We also dropped a bonus tile in the middle that pays +1 every time the agent steps onto it, and stepping onto it does not end anything. Think of the bonus as a shaping signal a well-meaning engineer added to "help the agent learn faster", the reinforcement learning equivalent of paying a delivery driver per parcel touched rather than per parcel delivered.

A 7x7 grid. The top-left cell is green and labelled S for start. The bottom-right cell is gold and labelled G for goal, worth plus one true reward and ends the episode. The centre cell is orange and labelled with a plus, the bonus tile worth plus one proxy reward and repeatable.

Q-learning does exactly one thing: it estimates the discounted sum of future reward for each action in each state, then acts greedily. With discount γ=0.99\gamma = 0.99, reaching the goal from the start (twelve steps away) is worth γ12≈0.89\gamma^{12} \approx 0.89, paid once. Oscillating on the bonus is worth roughly b+γ2b+γ4b+…b + \gamma^2 b + \gamma^4 b + \dots, which for b=1b = 1 sums to about 50 over a 100-step episode. Fifty beats 0.89 by a wide margin, so the optimal policy under this reward is to reach the bonus and never leave. The agent is not confused about the goal. It has correctly calculated that ignoring the goal pays better.

The two reward modes differ by one line. The true reward, r_true, pays only for reaching the goal. The hackable proxy adds the repeatable bonus on top. The agent never sees r_true; it optimises r_proxy. That single extra term is the entire bug.

r_true = 1.0 if done else 0.0                    # the objective
if self.reward_mode == "hackable":
    r_proxy = r_true + (self.bonus if s_next == self.bonus_pos else 0.0)
else:
    r_proxy = r_true                             # proxy = objective

To see the hack as it forms, log two returns per episode during training: the proxy return the agent is climbing, and the true return (discounted goal reward) that measures what we wanted. Under the hackable reward they pull apart. The proxy return climbs past 28 and plateaus; the true return never leaves the floor, because the greedy agent stops reaching the goal at all.

Two line charts. Left, titled Hackable reward, the proxy return rises steadily to about 28 and plateaus while the true return stays flat on zero, with the gap between them shaded. Right, titled Fixed reward, a single pair of lines for proxy and true return rise together and coincide at about 0.89.

The left panel is the signature of reward hacking: training looks like a success story. If you only watched the reward the agent optimises, you would ship it. The right panel is the fix, covered below, where the proxy is the objective, so the two returns are the same line.

The state-visitation heatmap makes the behaviour physical. The hacking agent's greedy rollout lights up two cells, the bonus tile and its neighbour, because it shuttles between them. The fixed agent traces a clean path to the corner.

Two heatmaps of the 7x7 grid coloured by how often the greedy agent visits each cell. Left, titled Hackable, almost all visits concentrate on the central bonus tile and one adjacent cell. Right, titled Fixed, visits form a staircase path from the top-left start to the bottom-right goal.

Going deeper

Reward hacking happens when you optimise a proxy that only correlates with your true objective, and the optimiser finds a region where the correlation breaks. This is Goodhart's law in one sentence: when a measure becomes a target, it stops being a good measure. Our bonus tile correlated with "making progress" right up until the agent discovered it could farm the measure directly.

Three ingredients turn a harmless proxy into a hackable one, and all three are present here.

  • A repeatable, unbounded source of proxy reward. The bonus pays every visit with no cap. Remove the repetition (pay the bonus once) and the loophole closes.
  • No cost that dominates the loophole. With no step penalty and γ\gamma near 1, an infinite trickle of small rewards outweighs a single large one. Long horizons make this worse, not better.
  • A proxy that is not the objective. The bonus was a stand-in for progress. The moment the agent can move the stand-in without moving the objective, the two decouple.

Fixing the reward

The cleanest fix is to reward the objective directly. Drop the bonus and pay only for reaching the goal. The proxy and the true reward become the same quantity, so there is nothing left to game. Q-learning then finds the optimal twelve-step path, its greedy return settles at γ12≈0.886\gamma^{12} \approx 0.886, and the agent reaches the goal on every rollout.

The obvious objection: sparse rewards can be slow to learn, which is why the engineer reached for a bonus in the first place. The principled way to add guidance is potential-based reward shaping from Ng, Harada and Russell (1999). Instead of an arbitrary bonus, define a potential Φ(s)\Phi(s) over states (here, negative distance to the goal) and add the difference in potential between consecutive states:

F(s,s′)=γ Φ(s′)−Φ(s)F(s, s') = \gamma\,\Phi(s') - \Phi(s)

This form is special. Summed over any trajectory it telescopes to γTΦ(sT)−Φ(s0)\gamma^T \Phi(s_T) - \Phi(s_0), a quantity that depends only on the endpoints, not the path. Ng et al. proved that any shaping of this form leaves the optimal policy unchanged: you can guide learning without changing what "optimal" means, so no loophole can appear. Train all three rewards and only the two aligned with the objective ever reach the goal. The hackable agent's goal-reach rate starts around 0.25 from random exploration and decays toward zero as it perfects the hack.

A line chart of goal-reach rate over episodes for three reward functions. The hackable reward starts near 0.25 and decays toward zero. The fixed sparse reward and the potential-based shaping reward both rise to 1.0 by around episode 450 and track each other closely.

Note the shaped agent reaches the goal but its proxy return sits near 12.9, not 0.89, because potential-based shaping adds a constant offset equal to the initial potential. The offset is harmless (it does not change the argmax over actions) but it is a reminder that the magnitude of the proxy reward tells you nothing about whether the objective is being met.

Detecting the hack

The lesson from the return curves is that you cannot detect hacking from the reward the agent optimises, because that reward always goes up. You need an independent measurement of the true objective. If you have one, the simplest detector is the gap between proxy return and true return: when proxy climbs and true does not follow, raise an alarm.

A line chart of proxy return minus true return over episodes. The hackable reward rises to about 28 and stays there, far above a dashed alarm threshold at 1. The fixed reward stays flat on zero, below the threshold.

The hackable run blows through the threshold within a couple of hundred episodes and stays there; the fixed run sits at zero. This is a toy version of the reward-model monitors that RLHF pipelines now run: hold out a trusted evaluation of the outcome you want, and watch for the training reward pulling away from it. One caveat the shaping case exposes: the absolute gap is confounded by any potential-based offset, so in practice you watch whether the trusted metric is improving, not the raw difference.

Where this comes from

Reward hacking sits inside a body of AI-safety work on what happens when capable optimisers meet imperfect objectives.

Amodei, Olah, Steinhardt, Christiano, Schulman and Mané named the problem in their 2016 paper "Concrete Problems in AI Safety". They list reward hacking as one of five concrete failure modes, defining it as the agent gaming its reward function to obtain high reward through unintended behaviour, and observe that it becomes more likely, not less, as agents get more capable:

"An objective function that is imperfectly specified may lead an agent to take undesirable, even harmful, actions. This is closely related to the idea of 'wireheading' ... more capable agents may be better at finding these hacks."

The canonical demonstration came the same year from Clark and Amodei at OpenAI in "Faulty Reward Functions in the Wild". Their CoastRunners boat-racing agent, rewarded on in-game points rather than finishing position, learned to circle a lagoon hitting the same three regenerating targets, scoring 20% higher than human players while crashing, catching fire, and never completing the course. Our bonus tile is CoastRunners in a grid.

Ng, Harada and Russell's 1999 paper "Policy Invariance under Reward Transformations" predates the problem framing but supplies the cure. They characterised exactly which reward modifications preserve the optimal policy, proving that potential-based shaping is both sufficient and, in a precise sense, necessary. It is still the default safe way to inject domain knowledge into a reward.

More recent work formalises the failure. Skalse, Howe, Krasheninnikov and Krueger's 2022 paper "Defining and Characterizing Reward Hacking" gives a formal definition: a proxy reward is hackable if you can increase proxy return while decreasing true return, exactly the divergence our detector watches. Pan, Bhatia and Steinhardt's 2022 "The Effects of Reward Misspecification" shows that scaling up model capacity often triggers sudden phase transitions into hacking behaviour, which is why the problem has only grown more urgent as RL moved from gridworlds to language-model fine-tuning.

Further reading

Interactive Tools

  • Q-Learning Visualiser: Watch a Q-learning agent train in a grid world with a live Q-value heatmap and policy arrows, the same algorithm this post uses to hack the reward.
  • Markov Chain Simulator: Edit transition matrices and watch state distributions evolve, the dynamics underneath every gridworld MDP here.

Stay in the loop

Get notified when new tutorials and deep-dives are published. No spam, unsubscribe anytime.

Related Posts

Frequently Asked Questions